Rename old files with last modification date

Hi everyone,

I have files like file1_Mod.txt, file2_Mod.txt. I want to rename the old files with the last modification date. I write the below script to rename with current date, but I don�t know how to use "date -r" to get the last modification date with the same format I have below (dd-mm-yyyy_hhmmss).

The ouput I would like is:
file1_Old_dd-mm--yyyy_hhmmss.txt
file2_Old_dd-mm--yyyy_hhmmss.txt

Script what I have so far.

for each in *Mod.txt;
do
mv $each $(basename $each Mod.txt)Old_$(date +"%d-%b-%Y_%H%M%S").txt
done

May somebody help me with this issue.

Thanks in advance.

Use:

$(date -r $each +"%d-%b-%Y_%H%M%S")

Hi Chubler_XL,

I replace follow your suggestion and it works nice. Thank you for your help.

The only thing is I get errors like shown below when the file has spaces in the name.
The only way to fix this is replace spaces (" ") with underscores ("_") or is there other way using basename, each?

$ for each in *Mod.txt;
do
mv $each $(basename $each Mod.txt)Old_$(date -r $each +"%d-%b-%Y_%H%M%S").txt
done
basename: extra operand `21-09-2009_Mod.txt
Try `basename --help' for more information.
date: extra operand `21-09-2009_Mod.txt'
Try `date --help' for more information.
mv: target `Old_.txt' is not a directory

Thanks for your help so far.

for each in *Mod.txt;
do
  NEWNAME=$(basename "$each" Mod.txt)Old_$(date -r "$each" +"%d-%b-%Y_%H%M%S")
  mv "$each" "$NEWNAME"
done
for each in *Mod.txt;
do
  NEWNAME=${each%_*}_Old_$(date -r $each +"%d-%b-%Y_%H%M%S").txt
  mv "$each" "$NEWNAME"
done

Hi Chubler_XL, thanks for your reply, it works now even if the file has spaces within its name, thank you.

Hi rdcwayx, thanks for your help too, I`ve tested your script and I`m not sure what is missing, I`ve made changes trying to fixit but is failing when the files has spaces in its name.

Thanks anyway.

Best regards