Shell – Append same timestamp to multiple filenames

datefilenamesshelltimestampsvariable

I have several files that I ftp each hour. The receiving system needs to have some sort of identifier that they came from the same batch, so I would like to append a timestamp to the filename. That alone is fairly easy, but since I want each file to have the same timestamp (so it can serve as the batch identifier), I cannot figure out how to do this.

So, I have:

file1.txt
file2.txt
file3.txt

And I want to have:

file1_20141110184303.txt
file2_20141110184303.txt
file3_20141110184303.txt

Any use of the date +%Y%m%d%H%M%S after the first use will obviously result in a different values in seconds, so I would like to have the first timestamp appended to the remaining files.

Best Answer

Just store the value of date +%Y%m%d%H%M%S in a variable:

x=$(date +%Y%m%d%H%M%S)

and later on

mv file1 file1_$x.txt
mv file2 file2_$x.txt
...

or in a loop for all *.txt files

for file in *.txt; do echo mv "$file" "${file%.txt}"_$x.txt; done

(remove echo if you are happy with what you see on the screen)

Related Question