2

I have a file named file1.txtcontaining file names like below :

filea.txt
fileb.txt
filec.txt

I want to copy the files listed in file1.txt to another folder. What is the UNIX command to use? (the shell is ksh88 if that's relevant).

  • Are the file names in file1.txt using full paths? or are all of these files in the same directory? – Eric Aug 30 '13 at 21:36
4

Your format assumes that no file names have newlines in them, which is not ideal (newlines are legal in filenames). You also don't mention your shell. However, in a POSIX shell, you can do this:

while IFS= read -r file; do
    cp -- "$file" new_dir/
done < file

In bash, it might be faster to pass them all to cp in one go, however (as long as you're below ARG_MAX):

files=()

while IFS= read -r file; do
    files+=( "$file" )
done < file

cp -- "${files[@]}" new_dir/

...or, the same thing, if you have bash4+:

mapfile -t files < file
cp -- "${files[@]}" new_dir/
  • I typed your lines in a file and execute that file.I think my shell is bash but your suggestion didn't work. – Crystal Aug 30 '13 at 14:55
  • mapfile -t files < filecp "${files[@]}" /ettdd/SPECS/tpl/TEMP_TFRW2 – Crystal Aug 30 '13 at 14:56
  • Sorry I meant to say :mapfile -t files < /ettdd/SPECS/tpl/list_TFRW2.txt cp "${files[@]}" /ettdd/SPECS/tpl/TEMP_TFRW2 – Crystal Aug 30 '13 at 14:56
  • @Crystal What is the output of echo "$0"; echo "$BASH_VERSION"? Try the first example instead, it should work in any POSIX shell. The mapfile example will only work on bash4+. What error messages are printed? – Chris Down Aug 30 '13 at 15:09
  • I save your first set of codes in a file called cpNmv and execute it. The error is : cpNmv: syntax error at line 5 : `done' unexpected – Crystal Aug 30 '13 at 15:46
3

With GNU tools:

xargs -rd '\n' cp -t /dest/folder -- < file1.txt

POSIXly:

sed 's/./\\&/g' < file1.txt | xargs sh -c 'exec cp -- "$@" /dest/dir' sh
  • For the above suggestion using sed, where should I use file1.txt? – Crystal Aug 30 '13 at 16:26

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.