Bash – Deleting files older than 30 days based on filename as date

bashdatefilenameslinuxrm

If I have a folder of files with their filenames as the date they were created:

2019_04_30.txt
2019_04_15.txt
2019_04_10.txt
2019_02_20.txt
2019_01_05.txt

How would I compare the files names against todays current date

$ date "+%Y_%m_%d"
>>> 2019_04_30

If the file names date is greater than 30 days then delete it. I would expect to end up with

2019_04_30.txt
2019_04_15.txt
2019_04_10.txt

I don't have to follow this naming convention, I could use a more suitable date format.

Best Answer

Here is a bash solution.

f30days=$(date +%s --date="-30 days")
for file in 20*.txt; do
    fdate=$(echo $file | tr _ -)
    fsec=$(date +%s --date=${fdate/.txt/})
    if [[ $fsec -lt $f30days ]]; then
        echo "rm $file"
    fi
done

I ended it with "echo rm $file" instead of really deleting your files, this will test the result before.

Related Question