Skip to content
Advertisement

Copy the newest two files and append the date

I’m looking for a way to copy the newest .gz files I have in Dir A to Dir B, and append the date to that files.

Example:

Dir A

  • cinema.gz
  • radio.gz
  • cars.txt
  • camera.gz

Dir B

  • cinema.gz.20200310
  • radio.gz.20200310

Using following command I can copy the newest .gz files to dirb

cp $(ls -1t /dira *gz | head -2) "dirb"

However I don’t find a way to change append the date to the filename.

I was trying something like this:

cp $(ls -1t /dira *gz | head -2) "dirb/*.$(date +%F_%R)"

But don’t works at all.

Your help please 🙂

Advertisement

Answer

for TO_MOVE in `ls -t *.gz | head -n2`; do 
    cp $TO_MOVE dirb/;
    mv dirb/$TO_MOVE dirb/$TO_MOVE.`date +%Y%m%d`;
done
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement