bash – How to search files by day of the week?

Question:

I have to delete compressed files that are backups of our Database following the following two rules:

  1. Must be more than 15 days old
  2. Do not delete backups on Sundays

I decided to use the find command, 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 -ctime parameter I can find files with a creation date greater 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 in its man page regarding days of the week. The closest I've been to so far is being able to print the filename along with its date formatted to display the day of the week using the -printf action:

$ 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 choose those that are not from the dom day and then apply the -delete .

I'm open to new options, not necessarily with the find command, it may be using pipes or whatever works for this case. Help me see the light.

Upgrade

@Gilles answer helped me find my way, however I had to modify the last part a bit. The final sentence 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

Answer:

With pipes: we filter the files for Sunday, then we remove the day.

LC_TIME=es_ES find /backups/db/ -type f -ctime +15 -name "*.sql.gz" -printf '%p %Aa\0' |
sed -z -e '/dom$/d' -e 's/ [^ ]+$//' |
xargs -0 rm

If you have an old version of sed that does not have -Z , and there are no special characters (spaces, \"' ) in the filenames:

LC_TIME=es_ES find /backups/db/ -type f -ctime +15 -name "*.sql.gz" -printf '%p %Aa\n' |
sed -e '/dom$/d' -e 's/ [^ ]+$//' |
xargs -0 rm

Another option is to rename the files to indicate the day of the week.

Scroll to Top