Bash foreach loop

前端 未结 7 1217
别跟我提以往
别跟我提以往 2020-12-22 20:39

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.

相关标签:
7条回答
  • 2020-12-22 21:07
    cat `cat filenames.txt`
    

    will do the trick

    0 讨论(0)
  • 2020-12-22 21:08
    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 %"
    
    0 讨论(0)
  • 2020-12-22 21:14

    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)

    0 讨论(0)
  • 2020-12-22 21:16

    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
    
    0 讨论(0)
  • 2020-12-22 21:26

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

    0 讨论(0)
  • 2020-12-22 21:28

    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> _
    
    0 讨论(0)
提交回复
热议问题