Bash foreach loop

BashForeach

Bash Problem Overview


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.

Bash Solutions


Solution 1 - Bash

Something like this would do:

xargs cat <filenames.txt

The 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

Solution 2 - Bash

"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

Reference: http://www.cyberciti.biz/faq/linux-unix-bash-for-loop-one-line-command/

Solution 3 - Bash

Here is a while loop:

while read filename
do
	echo "Printing: $filename"
	cat "$filename"
done < filenames.txt

Solution 4 - Bash

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 %"

Solution 5 - Bash

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> _

Solution 6 - Bash

If they all have the same extension (for example .jpg), you can use this:

for picture in  *.jpg ; do
    echo "the next file is $picture"
done

(This solution also works if the filename has spaces)

Solution 7 - Bash

cat `cat filenames.txt`

will do the trick

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjohnlemonView Question on Stackoverflow
Solution 1 - BashGreg HewgillView Answer on Stackoverflow
Solution 2 - BashTom K. C. ChiuView Answer on Stackoverflow
Solution 3 - BashdogbaneView Answer on Stackoverflow
Solution 4 - BashDennis WilliamsonView Answer on Stackoverflow
Solution 5 - BashpaxdiabloView Answer on Stackoverflow
Solution 6 - BashIsrael PView Answer on Stackoverflow
Solution 7 - BashAlan DykeView Answer on Stackoverflow