Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I am new to linux. 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.

Please help.

share|improve this question
    
protip: ` syntax is deprecated. use $() instead. –  strugee Apr 8 at 10:51

2 Answers 2

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

cd "$fromPath" && xargs mv -t "$toPath" < "$file"
share|improve this answer
    
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 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 at 9:29
    
@GautamSomani yes it was copied from a windows machine. Thanks for the tip :) –  Mr_Green Apr 9 at 9:44

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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