I have to delete compressed files that are backups of our Database following the following two rules:
- Must be more than 15 days old
- Do not delete the backups of Sundays
I decided to use the command find
, I think it is the most complete of the search commands (at least the ones I know of).
The first rule is simple, using the parameter -ctime
I can find files with a creation date older than 15 days:
$ find /backups/db/ -type f -ctime +15 -name "*.sql.gz"
./gestagro_2015_11_01.sql.gz
./gestagro_2015_11_02.sql.gz
./gestagro_2015_11_03.sql.gz
(varios resultados)
Then, in the same find
I did not find anything similar on your man
page regarding days of the week. The closest I've come so far is being able to print the filename along with its date formatted to display the day of the week using the action -printf
:
$ find /backups/db/ -type f -ctime +15 -name "*.sql.gz" -printf "%p %Aa\n"
./gestagro_2015_11_01.sql.gz dom
./gestagro_2015_11_02.sql.gz lun
./gestagro_2015_11_03.sql.gz mar
(varios resultados)
The problem now is that I don't know how to filter those results again to pick those that are not of the day dom
and then apply the -delete
.
I am open to new options, not necessarily with the command find
, it may be using pipes or whatever works for this case. Help me see the light.
Update
@Gilles answer helped me find my way, however I had to modify the last part a bit. The final statement is as follows:
$ find /backups/db/ -type f -ctime +15 -printf '%p %Aa\n' | sed -e '/dom$/d' -e 's/ [^ ]+$//' | cut -d' ' -f1 | xargs rm
With pipes: we filter the files for Sunday, then we remove the day.
If you have an old version of
sed
that doesn't have-Z
, and there are no special characters (spaces,\"'
) in the filenames:Another option is to rename the files to indicate the day of the week.