Bash foreach loop
I have an input (let's say a file). On each line there is a file name. How can I read this file and display the content for each one.
Something like this would do:
xargs cat <filenames.txt
xargs program reads its standard input, and for each line of input runs the
cat program with the input lines as argument(s).
If you really want to do this in a loop, you can:
for fn in `cat filenames.txt`; do echo "the next file is $fn" cat $fn done
Read more... Read less...
"foreach" is not the name for bash. It is simply "for". You can do things in one line only like:
for fn in `cat filenames.txt`; do cat "$fn"; done
Here is a
while read filename do echo "Printing: $filename" cat "$filename" done < filenames.txt
xargs --arg-file inputfile cat
This will output the filename followed by the file's contents:
xargs --arg-file inputfile -I % sh -c "echo %; cat %"
You'll probably want to handle spaces in your file names, abhorrent though they are :-)
So I would opt initially for something like:
pax> cat qq.in normalfile.txt file with spaces.doc pax> sed 's/ /\\ /g' qq.in | xargs -n 1 cat <<contents of 'normalfile.txt'>> <<contents of 'file with spaces.doc'>> pax> _
cat `cat filenames.txt`
will do the trick