Pooja
Pooja

Reputation: 165

How to append a dynamic string to the end of a copy's filename

Conside File is :

/home/dev/a1234.txt

I want to copy this file in /home/sys/ directory but I want to add some number on the file name while copying. Date1=date +%Y%m%d_%H:%M:%S Output should be :

/home/sys/a1234.txt.$Date1 

Number on the filename "1234" will be different everytime. so File name is not fixed.

Please suggest.

Upvotes: 1

Views: 4403

Answers (4)

fedorqui
fedorqui

Reputation: 290155

In two steps:

  • Copy the file to /home/sys.

    cp /home/dev/a1234.txt /home/sys
    
  • Move from a1234.txt to a1234.txt.130625. This way you can make it more general.

    mv /home/sys/a1234.txt{,$date} #is expanded to mv /home/sys/a1234.txt /home/sys/a1234.$date
    

As you indicate your file name will change, you can generalise my answer with $file_name instead of a1234.txt.

Test

$ touch a
$ date=23
$ mv aa{,$date}
$ ls
aa23

Upvotes: 0

William Breathitt Gray
William Breathitt Gray

Reputation: 11986

Use the date command to get the current date.

$ DATE=`date +%Y%m%d_%H:%M:%S`; NAME=a; EXT=txt; for i in {0..4}; do echo $NAME$i$.$EXT.$DATE; done
a0.txt.20130625
a1.txt.20130625
a2.txt.20130625
a3.txt.20130625
a4.txt.20130625

Change the echo line to be a cp:

$ DATE=`date +%Y%m%d_%H:%M:%S`; FROMDIR=/home/dev; TODIR=/home/sys; NAME=a; EXT=txt; for i in {0..4}; do cp $FROMDIR/$NAME$i.$EXT $TODIR/$NAME$i$.$EXT.$DATE; done

This is probably better in a bash script where you can modify it easier than a single liner:

#!/bin/bash

# get current date
DATE=`date +%Y%m%d_%H:%M:%S`;

# specify from directory and to directory for cp
FROMDIR=/home/dev;
TODIR=/home/sys;

# set base filename and extension
NAME=a;
EXT=txt;

# count from 0 to 4
for i in {0..4}; do
    # copy file and add date to end of new filename
    cp $FROMDIR/$NAME$i.$EXT $TODIR/$NAME$i$.$EXT.$DATE;
done

i increments from 0 to 4 in this example, while a filename of the form $NAME$i.$EXT is copied from $FROMDIR to TODIR -- with the current date in $DATE appended to the end of the copy's filename.

Upvotes: 0

vikingsteve
vikingsteve

Reputation: 40418

Something like this should get you on the way:

for i in $( ls /home/dev | grep 'a[0-9]*.txt$'); do
    cp /home/dev/$i /home/sys/$i.`date +%Y%m%d_%H:%M:%S`;
done

You can improve it by seeing if the file has already been copied, and prevent it from being copied a second time.

Upvotes: 1

Beta
Beta

Reputation: 99144

NAME=a1234.txt
cp dev/$NAME sys/$NAME.$Date1

Upvotes: 0

Related Questions