Deleting files older than 30 days based on filename as date

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.


With zsh:

zmodload zsh/datetime
strftime -s start '%Y_%m_%d.txt' $((EPOCHSECONDS - 30*86400))
echo -E rm -i 2*.txt(e:'[[ $REPLY > $start ]]':)

Remove the echo -E when happy.

On a GNU system and with the GNU shell (bash), you could do something approaching with:

start=$(date -d '30 days ago' +%Y_%m_%d.txt)
list=()
shopt -s nullglob
for file in 2*.txt; do
  [[ $file > $start ]] && list+=("$file")
done
if (( ${#list[@]} > 0)); then
  echo -E rm -i "${list[@]}"
fi