Using Find to Delete Files

If you have ever needed to delete file that are older then a given date in a linux enviroment FIND will give you what you are looking for. The basic command layout is
find %PATH% -type f -name %FILTER% -mtime +%DAYS% -print -delete

  • %PATH% This is the folder you want to delete the files from.
  • %FILTER% This file name search filter for deleting files.
  • %DAYS% This is the number of days the file must be older than.
  • -print This is optional and will print the name of the file being deleted
  • -delete This is what tells find to delete the file once it finds it.

Example

Lets say I wanted to delete all the PDF files in my /home/user/junk/ folder that were older then 30 days. I would use the following
find /home/user/junk/ -type f -name '*.pdf' -mtime +30 -print -delete

Take Ways

I have used this command to delete millions of files from a tmp folder that were the result of  automated process. The find command does use memory to build the file tree so you will need to bear that in mind when using it. Some of the tricks I have done to get around the millions of files and memory issue is to break out the %FILTER% into logical file name chunks so that I'm not parsing the whole tree at once.

Leave a Reply

Your email address will not be published. Required fields are marked *