Home > front end >  Renaming files in Linux to date minus one day
Renaming files in Linux to date minus one day

Time:02-03

I have a procedure (.sh) that extracts data and writes it to .csv files. The name we use for these .csv files we create based on this statement:

for f in $DATA_DIR/*.csv 
do 
      mv $f ${f%.csv}$(date " __$FROM_DATE""_$FROM_DATE""000000.csv")
      
done

Where the $FROM_DATE is the variable when running the shell script. This could be any date we want to extract. Now I would like to name the file the $FROM_DATE but then the day before. So the name should be one day prior to the data extracted. I found this on Google but not sure how to implement this in my existing statement:

date -d"20220122 -1 day"  %Y%m%d

Any help is much appreciated!

CodePudding user response:

Assuming the format of FROM_DATE is YYYYMMDD the date command in your first script is useless. It does nothing except echoing what you pass it. And your second date command does exactly what you want. So all in all the following should make it:

for f in $DATA_DIR/*.csv; do
  y=$(date -d"$FROM_DATE -1 day"  %Y%m%d)
  mv "$f" "${f%.csv}__${y}_${y}000000.csv"
done
  •  Tags:  
  • Related