1. A simple approach:
echo 'Hello, world.' > foo.txt
< file.txt xargs -L 1 cp foo.txt
cat command is vastly overused;
when you see
cat filename | command,
you can change it to
command < filename or,
< filename command.
-L 1 option to
xargs tells it
to read only one line from
file.txt at a time;
file2 (on separate lines),
xargs will run
cp foo.txt file1
cp foo.txt file2
I presume the rest is self-explanatory.
If you want to put this all on one line, just join the lines with
echo 'Hello, world.' > foo.txt && xargs -L 1 cp foo.txt < file.txt && rm foo.txt
I moved the
< file.txt to the end of the
which is where people usually put it.
2. More flexible
You will probably want to do something more complex and sophisticated
than writing the same single line to each file.
xargs sh -c 'for f do echo "Hello, world." > "$f"; done' sh < file.txt
passes the filenames to an invocation of the shell (
which can then do anything to the named file (referenced as
that you could do from the shell prompt.
And, obviously, with this method,
you don’t need to create and delete a temporary file.
3. Without using
You can simplify the above to
while IFS= read -r f
echo 'Hello, world.' > "$f"
done < file.txt
which is essentially the same as the previous answer,
except this time the shell reads the
so you don’t need