I want to delete file not by date access or created, but by filename. The filenames will be dates and I want to have a cronjob run once a week that will purge filename dates older than 7 days. I could do afind /my/directory -type f -name '*file-name.yyyy-mm-dd.qz' -deleteBut I would have to change the script on a weekly basis to run. I would like to avoid having to modify the job every week.
How do I delete file by filename that are set as dates?
command line;files;find;rm
Here is a more robust form that correctly handles spaces (or even newlines) in filenames and directory names.find . -type f -name '*.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].qz' -exec sh -c 'fdate=${1%.qz}; fdate=${fdate##*.}; [ $fdate < $(date +%F -d 7 days ago) ] && rm $1' find-sh {} \;This involves a lot of shell trickery that might look alien to some people, so let's break it down:Starting in the current directory, recursively find all regular files...find . -type f...whose names end in the exact pattern .YYYY-MM-DD.qz...-name '*.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9].qz'...then, run a shell command on each matching file (note the single quotes)...-exec sh -c '...which first strips off the trailing .qz...fdate=${1%.qz};...then strips off the leading extra part, leaving only YYYY-MM-DD...fdate=${fdate##*.};...and compares that string to see if it sorts (lexically) earlier than YYYY-MM-DD of the date seven days ago...[ $fdate < $(date +%F -d 7 days ago) ]...and if so, removes the file...&& rm $1'...and we'll use find-sh as the script name (i.e. $0) to be used for error reporting...find-sh...and set the filename found by find to parameter one ($1) of the inline shell script.{} \;