Remove old files by date in filename

I have backup scripts that create files with the backup date in their filename, in ISO 8601 format, as generated by date -I, as follows:


This is year-month-day:


Every month I want to delete all old backups, except those from the current month or from the first of each month.

This will leave me with backups from the 1st of every month before this month alongside all backups from this month. If I did this on 3rd March 2015 I could end up with files as follows:


You can use the find command to do this:

find . -type f -name "mirrors.tgz-`date +'%Y'`-*" -not -name "mirrors.tgz-`date +'%Y-%m'`-*" -not -name "mirrors.tgz-`date +'%Y'`-*-01" -exec ls {} \;

This will find all files in the current directory with a name containing a date from this year, but not those with a date from this month, nor those with a date on the 1st of a month, and run ls on them.

I replaced the rm command with ls in the -exec ls {} \; to list the files rather than delete them, because it should be tested first!

A more general command is as follows, which looks for any file and not just those starting with ‘mirrors.tgz’ (still with the above date conditions):

find . -type f -name "*-`date +'%Y'`-*" -not -name "*-`date +'%Y-%m'`-*" -not -name "*-`date +'%Y'`-*-01" -exec ls {} \;

Last modified: 13/12/2015 Tags: ,

This website is a personal resource. Nothing here is guaranteed correct or complete, so use at your own risk and try not to delete the Internet. -Stephan

Site Info

Privacy policy

Go to top