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.

  • protip: ` syntax is deprecated. use $() instead. – strugee Apr 8 '14 at 10:51
3
file=/path/to/filenames.txt
fromPath=/root/Backup/upload/
toPath=/root/Desktop/custom/upload/

cd "$fromPath" && xargs mv -t "$toPath" < "$file"
  • 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 Apr 8 '14 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. – Gautam Somani Apr 9 '14 at 9:29
  • @GautamSomani yes it was copied from a windows machine. Thanks for the tip :) – Mr_Green Apr 9 '14 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.