Append date/timestamp to existing files

Viewed 592

There are few files in a directory. I would like to find all the files based on wildcard criteria and then rename it by appending a date or timestamp field to it using single line command

Example : foo1.txt foo1.log foo2.txt foo2.log

I want to find all .log files and rename them by appending date field to it

Expected output : foo1.txt foo1_20210609.log foo2.txt foo2_20210609.log

2 Answers

I would use a "for" loop over the wildcard list of matches and then use parameter expansion and command substitution to splice out the rest:

for file in *.log
do
  echo mv -- "$file" "${file%.log}_$(date +%Y%m%d).log"
done

The pieces in the middle break down as:

  • mv -- -- invoke "mv" and explicitly tell it that there are no more options; this insulates us from filenames that might start with -i, for example
  • "${file%.log} -- expands the "$file" variable and removes the ".log" from the end
  • _ -- just adds the underscore where we want it
  • $(date +%Y%m%d) -- calls out to the date command and inserts the resulting output
  • .log -- just adds the ".log" part back at the end

Remove the "echo" if you like the resulting commands. If you want a static timestamp, then just use that text in place of the whole $(date ...) command substitution.

On your sample input, but with today's date, the output is:

mv -- foo1.log foo1_20210610.log
mv -- foo2.log foo2_20210610.log
ls | perl -lne '$date=`date '+%Y%m%d'`; chomp($date); `mv $_ $_$date`;'
  1. ls the file
  2. pipe it into a perl script
  3. e option executes in line
  4. n option splits the input into lines
  5. l option adds new line to each

back ticks execute unix commands

Related