2

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

temp_30042019
temp_15042019
temp_10042021
temp_20022020
temp_21102022
temp_22102022
temp_01112022

How would I compare the files names against todays current date

$ echo `date +"%d%m%Y"`
#output:
01112022

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

temp_21102022
temp_22102022
temp_01112022
1
  • No need to use echo date +"%d%m%Y", you can just use: date +"%d%m%Y" Commented Nov 1, 2022 at 9:27

1 Answer 1

1

Using a bash script:

#!/usr/bin/bash

older30days=$(date --date 'now - 30 days' '+%Y-%m-%d')

echo Checking files before $older30days

for file in ./temp_*; do
   cdate="$(echo ${file#*_} | awk -v FS='' -v OFS='-' '{print $5$6$7$8,$3$4,$1$2}')"

   if [[ $cdate < $older30days ]]; then
      echo "Removing file: " $file
      rm $file
   fi
done

You do not need to print with echo in the code above but it should be useful to understand what is actually happening in your script.

Using echo ${file#*_} | awk -v FS='' -v OFS='-' '{print $5$6$7$8,$3$4,$1$2} I'm parsing the date of your filenames into a valid date so I will be able to compare using an if condition. For example, having this filename:

temp_15042019

With the code above I'm parsing it into:

2019-04-15 #YYYY-MM-DD

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .