Bash foreach 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4162821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:52:03  来源:igfitidea点击:

Bash foreach loop

bashforeach

提问by danidacar

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.

我有一个输入(比方说一个文件)。每行都有一个文件名。如何读取此文件并显示每个文件的内容。

回答by Greg Hewgill

Something like this would do:

像这样的事情会做:

xargs cat <filenames.txt

The xargsprogram reads its standard input, and for each line of input runs the catprogram with the input lines as argument(s).

xargs程序读取它的标准输入,以及用于输入的每一行的运行cat与输入线作为参数(一个或多个)程序。

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

回答by Tom K. C. Chiu

"foreach" is not the name for bash. It is simply "for". You can do things in one line only like:

“foreach”不是 bash 的名称。它只是“为了”。您只能在一行中执行以下操作:

for fn in `cat filenames.txt`; do cat "$fn"; done

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

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

回答by dogbane

Here is a whileloop:

这是一个while循环:

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

回答by Paused until further notice.

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

回答by paxdiablo

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

回答by Alan Dyke

cat `cat filenames.txt`

will do the trick

会做的伎俩

回答by Israel P

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

如果它们都具有相同的扩展名(例如 .jpg),您可以使用:

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

(This solution also works if the filename has spaces)

(如果文件名有空格,此解决方案也适用)