I have a .txt file containing 150 different ID number on each line like so:


Located in the same directory as the .txt file, I have 300 folders and I want to copy only the folders whose names match those listed in the .txt file into a folder called New_Folder. Is there a simple way this can be done?

2 Answers 2


One way would be to use xargs

xargs -a list.txt cp -t path/to/New_Folder/ -R --

If you wish to use a shell loop, then use while e.g.

while IFS= read -r dir; do
  cp -t path/to/New_Folder -R -- "$dir"
done < list.txt
  • I initially tried using xargs command earlier and I get the following output cp: cannot stat
    – LDG
    Jul 11, 2016 at 23:46
  • It looks like it's reading each line within the txt file as one long name like this 12345/r15876/r19643
    – LDG
    Jul 11, 2016 at 23:49
  • @LDG perhaps your file has DOS-style or Mac-style line endings? Jul 11, 2016 at 23:56
  • Yes it does. What might be the best way to get around this issue? Sorry if this is a trivial question, I'm new to all this and have literally no idea what I'm doing.
    – LDG
    Jul 11, 2016 at 23:57
  • 2
    Why not tr '\r' '\n' < list.txt | xargs cp -t /path/blabla ? Should work for both DOS and Mac files on a Linux-like machine. (DOS files would get extra lines which will be thrown away by xargs).
    – grochmal
    Jul 12, 2016 at 0:19

Something like:

for dir in `cat textfile.txt`; do
    cp -a "$dir" New_Folder/
    echo Copied $dir


Note: if any of the directory names in textfile.txt have spaces in them, it just got harder.

Also: was there something significant about the lines in your .txt file? Were the directories on each line supposed to be treated differently from the directories on other lines?

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.