3

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.

  • You can use YYYY-MM-DD for your filenames, it would help when using "date" functions then – darxmurf Apr 30 at 11:09
4

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.

4

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.