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:

mirrors.tgz-2015-12-31

This is year-month-day:

mirrors.tgz-Y-m-d

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:

...
mirrors.tgz-2014-11-01
mirrors.tgz-2014-12-01
mirrors.tgz-2015-01-01
mirrors.tgz-2015-02-01
mirrors.tgz-2015-03-01
mirrors.tgz-2015-03-02
mirrors.tgz-2015-03-03

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