Linux Shell script to copy files from one location to another location
Solution 1
srcdir="home/install/project1/folder1"
dstdir="home/install/project1/folder2"
d=$(date +%m%d%y)
for srcfile in ${srcdir}/*
do
dstfile=$(basename $srcfile)
dstfile=${dstfile/\./${d}\.}
cp $srcfile $dstdir/$dstfile
done
Solution 2
You can do it in 2 steps, first cp
:
cp -rp source/ target/
Then use rename
. But you should use Ubuntu flavor of it, which is actually Perl script. For Redhat, you might be able to install or download it from https://metacpan.org/module/rename. Unfortunately, native Redhat/Fedora rename does not support Perl regular expressions and will not work for this.
At any rate, use Perl-ish rename
like this:
cd target
rename 's/\.dat$/091012.dat/' *
You can even use it recursively by combining it with find
and xargs
, something like:
find | xargs rename 's/\.dat$/091012.dat/'
Related videos on Youtube
G M Ramesh
Updated on September 18, 2022Comments
-
G M Ramesh over 1 year
I have a folder in my server which contains some files. These are automated that means everyday we get new files automatically which will overwrite the old ones. So want to take a back up for this data. How can i copy all these files in to a another folder by renaming the files with current date while copying.
ex : i have a folder named folder1 which contains 4 files. path for this folder is home/install/project1/folder1
aaa.dat bbb.dat ccc.dat ddd.dat
now i want to copy all these four files in to a different folder named folder2. path for this folder is home/install/project1/folder2. while copying these files i want to rename each file and add the current date to the file. so my file names in folder2 should be..
aaa091012.dat bbb091012.dat ccc091012.dat ddd091012.dat
I want to write a
Linux
shell script for this. Please give me some idea or some sample scripts related to this.-
G M Ramesh about 11 years@JimGarrison, i tried this command...$ mv /directory_one/* /directory
-
G M Ramesh about 11 years@JimGarrison, for unix shell , i know the script how to copy files but for linux i dont know... if the unix commands works for linux also then its ok. i can make it out...
-
Ex Umbris about 11 years98% of Unix commands have identical or very similar counterparts in Linux.
-
G M Ramesh about 11 yearsI am using Red Hat
-
G M Ramesh about 11 years@JimGarrison, thank u Jim... i will check that command now
-
-
ruakh about 11 yearsThere are a few problems with that script; most notably,
$srcfile
will actually just be equal to$srcdir
. -
Tuxdude about 11 yearsJust add a note that this script would not copy any files present in sub-directories of
srcdir
to ensure it is what OP expects. -
ruakh about 11 yearsNow
$dstfile
will be e.g.home/install/project1/folder1/aaa091012.dat
, so$dstdir/$dstfile
will be e.g.home/install/project2/folder2/home/install/project1/folder1/aaa091012.dat
. -
maverick about 11 yearsNice, @ruakh - edited again