Finding and deleting old files

Here’s a nifty little unix command line snippet that I found a while back while trying to find a way to clear images from a directory on a regular basis. It lets you manipulate files that are more than a specified age. For example, if you wanted to see all files in the /var/log directory that were more than two weeks old, you could do something like this:

$ find /var/log -mtime -14 -type f -exec ls -al {} \;

Deleting files can be done in a similar fashion. To delete any files in the current directory with a “.jpg” extension, one could probably do something like:

$ find /home/you/yourpictures -mtime -14 -type f -name "*.jpg" -exec rm -f {} \;

As with many unix commands, go slowly and carry a big backup. Be careful. The person who originally posted this snippet did so with a word of warning that I will repeat:

Find is very powerful, and I suggest you do some reading BEFORE you do any removing using “find”. Also, as a test you can replace the “rm -rf” with “ls -la” to get a list of all the files that would be removed.

So consider yourself warned. Here’s the manual page for find, in case you are interested. Wikipedia also has a nice entry that includes plenty of examples for you to practice with.

Post a Comment

Your email is never shared. Required fields are marked *