1

I am trying to copy files from one path to another path. I have a text file which has all names of files in the following pattern:

file-1.txt
file-2.pdf
file-3.ppt
....

I created a .sh file with the following code:

 #!/bin/bash
file=`cat filenames.txt`;
fromPath='/root/Backup/upload/';
toPath='/root/Desktop/custom/upload/';
for i in $file;
do
 filePath=$fromPath$i
 #echo $filePath
 if [ -e $filePath ];
 then
   echo $filePath
   yes | cp -rf $filePath $toPath
 else
   echo 'no files'
 fi
done

The above code is copying only the last file name from the text instead of all to the destination path.

1
  • protip: ` syntax is deprecated. use $() instead.
    – strugee
    Commented Apr 8, 2014 at 10:51

2 Answers 2

3
file=/path/to/filenames.txt
fromPath=/root/Backup/upload/
toPath=/root/Desktop/custom/upload/

cd "$fromPath" && xargs mv -t "$toPath" < "$file"
3
  • The problem was that each line in the text file was terminating differently instead of just \n.. may be like \n\r.. I run sed 's:\r$::' -i filename.txt at the text file path and run my script again. which worked fine. Anyway thanks for your short answer +1 :)
    – Mr_Green
    Commented Apr 8, 2014 at 11:24
  • 1
    @Mr_Green If your file had \n\r as new line characters, then may be it was copied from a windows machine. You may run the command "dos2unix filename" and then run your original script. It should work then. Commented Apr 9, 2014 at 9:29
  • @GautamSomani yes it was copied from a windows machine. Thanks for the tip :)
    – Mr_Green
    Commented Apr 9, 2014 at 9:44
1

You might take a look at rsync, if you're not already familiar with it. This looks like a problem that shouldn't really require a script of its own.

Take a look here, or use your Google foo.

The rsync option you need is probably --files-from.

The rsync incantation will be something like:

rsync --files-from filenames.txt /root/Backup/upload /root/Desktop/custom/upload

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .