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.
Asked
Active
Viewed 3.8e+01k times
7 Answers
266
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

Greg Hewgill
- 951,095
- 183
- 1,149
- 1,285
-
3Both of these don't work when the filenames contain spaces. – mivk Nov 09 '18 at 09:48
-
@mivk you can escape the space – Toochka Jan 13 '20 at 20:02
50
"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/

Peter Gluck
- 8,168
- 1
- 38
- 37

Tom K. C. Chiu
- 776
- 6
- 17
23
Here is a while
loop:
while read filename
do
echo "Printing: $filename"
cat "$filename"
done < filenames.txt

dogbane
- 266,786
- 75
- 396
- 414
-
This should be best approach. You with to use the '-r' & '-d' option with `read` – sjsam May 21 '16 at 06:23
-
2Unlike most other answers here, this one actually works, even when file names contain spaces. – mivk Nov 09 '18 at 09:53
5
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 %"

Dennis Williamson
- 346,391
- 90
- 374
- 439
4
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> _

paxdiablo
- 854,327
- 234
- 1,573
- 1,953
4
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)

Israel P
- 41
- 3
-
2I think there are situations in which it is useful to surround `*.jpg` with quotes, IIRC: `for picture in "*.jpg";`... – Tom Russell Mar 13 '21 at 05:20