How to delete all files before a certain date in Linux
Posted on: September 15, 2015
If you have a list of files, but you only want to delete files older the a certain date, for example, a maildir folder with 5 years worth of email, and you want to delete everything older then 2 years, then run the following command.
find . -type f -mtime +XXX -maxdepth 1 -exec rm {} \;
The syntax of this is as follows.
- find – the command that finds the files
- . – the dot signifies the current folder. You can change this to something like /home/someuser/mail/somedomain/someemail/cur or whatever path you need
- -type f – this means only files. Do not look at or delete folders
- -mtime +XXX – replace XXX with the number of days you want to go back. for example, if you put -mtime +5, it will delete everything OLDER then 5 days.
- -maxdepth 1 – this means it will not go into sub folders of the working directory
- -exec rm {} \; – this deletes any files that match the previous settings.