If you've ever wanted to look for a bunch of files and then delete them, you might have read carefully through man find. Or maybe not. A web search will show that you can achieve this using the -exec option of find. This has its peculiarities, and by reading through the man page, you will notice something fairly useful.
Enter the -delete option. This does what it says it will. It deletes what you found.
find /var/log/ -name '*.log' -type f -size +10M -delete
This will find all files anywhere under /var/log/ with the extension .log that are over 10 megabytes in size and delete them.find /home/user/ -type f -mtime +30 -delete
This will find all files anywhere under /home/user that were last modified more than 30 days ago, and delete them.
Some examples:
Of course I am not responsible for anything you may accidentally delete while playing with these examples. Please use with caution. They are only examples.
Even though the -delete option is probably a better way to remove files with find, I personally often find myself using the -exec method because I can throw an echo into the mix to get a dry run.
ReplyDeleteYou can do the same with -delete also but you would replace -delete with -print to show the files it's going to delete.
find /var/log/backup -type f -mtime +30 -print
or using the exec method:
find /var/log/backup -type f -mtime +30 -exec echo rm -f {} \;
Find offers some truly dangerous options to those who aren't careful, but its very hard to compete with the functionality it offers.