Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a file, file_copy, which has:

>cat file_copy
file1
file2
file3

I want to copy file1, file2, file3 from /source to /dest. One way I know how to do this is to just do:

for line in `cat file_copy` ; do cp /source/$line /dest; done

But I know that there is a better way, probably using find/xargs and/or awk, etc. What is the preferred way of doing this?

share|improve this question
add comment

1 Answer

up vote 4 down vote accepted

The best way to iterate over lines in a file is using while:

while read line; do cp /source/"$line" /dest/; done < file_copy

And while the above is good enough for most cases, a more robust solution (although rarely needed) is:

while IFS= read -r line; do cp /source/"$line" /dest/; done < file_copy

The IFS= prevents whitespace from being trimmed at the start and end of a line. -r prevents backslashes from being discarded.


Regarding your original command:

  • There's a useless use of cat.

  • You shouldn't read lines with for because it's prone to errors when your lines contain whitespace. In practice, if you find yourself using for with anything else than looping over file names generated by the shell (e.g. for f in *.csv), you're probably doing something wrong.

  • You should also quote your variables to prevent file names with spaces from being broken up into multiple arguments.

share|improve this answer
add comment

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.