Novice_Techie
Novice_Techie

Reputation: 444

Copy same files at multiple locations in UNIX

I have below 3 Files at source Location ${PDR}

PHONE_ABC.txt
PHONE_EFG.txt
PHONE_XYZ.txt

I need to copy same files at 3 different locations and add time and some text to it:

Target Location 1 ${LCT1}
Target Location 2 ${LCT2}
Target Location 3 ${LCT3}

Files at Location 1 should be as below:

PHONE_ABC_LCT1_20180914.txt
PHONE_EFG_LCT1_20180914.txt
PHONE_XYZ_LCT1_20180914.txt

Files at Location 2 should be as below:

PHONE_ABC_LCT2_20180914.txt
PHONE_EFG_LCT2_20180914.txt
PHONE_XYZ_LCT2_20180914.txt

Files at Location 3 should be as below:

PHONE_ABC_LCT3_20180914.txt
PHONE_EFG_LCT3_20180914.txt
PHONE_XYZ_LCT3_20180914.txt

Code Used

#!/usr/bin/ksh

cp ${PDR}/PHONE_*.txt ${LCT1}/
cp ${PDR}/PHONE_*.txt ${LCT2}/
cp ${PDR}/PHONE_*.txt ${LCT3}/

# define list of files
LCT1=${LCT1}/PHONE_*.txt
LCT2=${LCT2}/PHONE_*.txt
LCT3=${LCT3}/PHONE_*.txt

# grab time
dtstamp=`date +%Y%m%d`

# for LCT1
for file in ${LCT1}
do
    if [ ! -s ${file} ]
    then
        continue
    fi
    filebase=${file%.csv}
    mv ${file} ${filebase}_LCT1_${dtstamp}.txt
done

# for LCT2
for file in ${LCT2}
do
    if [ ! -s ${file} ]
    then
        continue
    fi
    filebase=${file%.csv}
    mv ${file} ${filebase}_LCT2_${dtstamp}.txt
done

# for LCT3
for file in ${LCT3}
do
    if [ ! -s ${file} ]
    then
        continue
    fi
    filebase=${file%.csv}
    mv ${file} ${filebase}_LCT3_${dtstamp}.txt
done

This is giving me what i require. But somehow i believe this code could be made more efficient and robust which i am not able to figure it out. Also on day 2 it keeps appending timestamp to the files at target location which i don't thing is good thing to do.

Any pointers to make this code look more efficient and good.

Upvotes: 0

Views: 40

Answers (1)

Andre Gelinas
Andre Gelinas

Reputation: 912

Something like that maybe :

#!/usr/bin/ksh

# grab time
dtstamp=$(date +"%Y%m%d")

cd ${PDR}
for file in PHONE_*.txt
do
    if [ ! -s ${file} ]
    then
        continue
    fi
    cp ${file} ${LCT1}/${file%.txt}_LCT1_${dtstamp}.csv
    cp ${file} ${LCT2}/${file%.txt}_LCT2_${dtstamp}.csv
    cp ${file} ${LCT3}/${file%.txt}_LCT3_${dtstamp}.csv
done

Upvotes: 1

Related Questions