This solution works using bash
's parmeter expansion / pattern matching and and will place the date before multiple file extensions such as tar.gz
:
mv "${file}" "${file%%.*}${dateNow}.${file#*.}"
# myfile.tar.gz -> myfile2023_01_24.tar.gz
The first part of this solution uses ${file%%.*}
to greedily match against the .*
at the end of the variable and cuts out that match returning the difference.
The end part, ${file#*.}
, works in the opposite way by lazily matching against the *.
pattern at the beggining of the variable and returning the difference.
If for example you want to place the date before just the first extension you can do this:
mv "${file}" "${file%.*}${dateNow}.${file##*.}"
# google.com.txt -> google.com2023_01_24.txt
I am assuming you have properly set the $dateNow
var, however if you haven't then you can use the date
command to insert the date:
mv "${file}" "${file%%.*}$(date +'%Y_%m_%d').${file#*.}"