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
pushdmakes 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)
-Rsearches recursive (including symbolic links)
-iignores case sensitive
-l(lower case L) outputs only the file name, not the actual matched line
-Eenables extended regular expressions
| uniqmakes sure we always have an unique list of file names
zipwill archive to the provided path using the files variable
-eencrypts with password
Hope you found this useful!