How to find files and zip them right where they were found

From LQWiki
Jump to navigation Jump to search

Find files and then Zip them in their discovered location:

Straight forward example:

find /etc/*/*.log -mtime +4 -execdir zip '{}'.zip '{}' \;


Brief explanation:

find /etc/*/*.log

This command searches for; all the files; in all the folders; under the etc folder, that have a .log suffix.


-mtime +4

This modifier will cause the find command to search for files that were last modified 4 days ago or more.


-execdir

This will make the following command execute in the directory of the discovered file(s).


zip '{}'.zip '{}' \;''

This is the ZIP command, the first parameter is the name of the output file (original file name + ZIP suffix).

The second parameter is received via the find command; it's the name of the file that need to be compressed.


After zipping the files, you may want to delete the original files, leaving only the compressed files.

You can delete the original files as follows:

find /etc/*/*.log -mtime +4 -delete


Note: Before you try this command!

Before you try the above commands, you may want to make sure that the find command, finds the files you want it to find.

You can do that like this:

find /etc/*/*.log -mtime +4 -exec ls -lt {} \;

Running the command will display a list of the files that have been discovered.


That's it.

I intentionally tried to keep it as simple as possible.

I hope you've found this helpful.