Mauserrifle.nl Tech and Life

    Home     Archive     Projects     Contact

Find Files by Content Using Grep and Zip Them Automatically

The Linux script in this article shows how to search files by content using grep and archive them automatically using zip with relative paths from the working directory defined.

#!/usr/bin/env bash

# Change the directory. Relative directory paths from here will be used zipping
pushd /path/to/files

# Get the files by searching for multiple words / regex patterns
files=$(sudo grep -RilE 'SMR League|Simresults|SMR.*?Hours' ./ | uniq)

# Zip the files with password encryption
zip -re /path/results.zip $files

# Revert back to the original directory
popd

Explained in detail

  • pushd makes sure we change the working directory, this is important to have relative paths in the zip later on
  • The files variable is assigned the output of the grep command that searches with three regex patterns (using an or statement)
    • -R searches recursive (including symbolic links)
    • -i ignores case sensitive
    • -l (lower case L) outputs only the file name, not the actual matched line
    • -E enables extended regular expressions
    • | uniq makes sure we always have an unique list of file names
  • zip will archive to the provided path using the files variable
    • -e encrypts with password
    • -r recursive


Hope you found this useful!

If you liked this post, you can share it with your followers!