This is based on the question here.
Problem:
- I have a .txt file listing file names I want to copy to the folder newfolder in the shell (Mac Terminal).
Approach, where filelist.txt contains file names (separated by \n), that I want to copy:
# version 1
for file in $(cat filelist.txt); do cp "$file" newfolder; done
Errors:
If I have file names in filelist.txt that contain dashes, whitespace, etc, the names are split up and I correctly get a No such file
error.
Here is how I try to address it (adding dbl quotes to the variable):
# version 2
for file in "$(cat filelist.txt)"; do cp "$file" newfolder; done
But this prints out all the file names (no splitting on whitespace) and does not copy anything.
Questions:
Adding quotes as above addresses the name splitting issue e.g. when I feed it to
echo
; why does it not work forcp
?What is the right way of doing this with
cat
andcp
? A comment in the answer linked above suggests the following:set -f;IFS=$'\n'
which fixes things but I have not idea what it does.
Any hints are much appreciated!
echo
, it does not actuallyecho line
,echo line 2
etc but rather echoline\nline2
etc? that is where i was mistaken that it was "fixed" ... – patrick Aug 10 '18 at 18:34