如何将shell命令应用到命令输出的每一行?

假设我有一些命令的输出(如ls -1 ):

 a b c d e ... 

我想依次对每一个应用一个命令(比如echo )。 例如

 echo a echo b echo c echo d echo e ... 

在bash中最简单的方法是什么?

这可能是最简单的使用xargs 。 在你的情况下:

 ls -1 | xargs -L1 echo 

您可以在每行上使用基本的前置操作:

 ls -1 | while read line ; do echo $line ; done 

或者,您可以将输出传递给sed以执行更复杂的操作:

 ls -1 | sed 's/^\(.*\)$/echo \1/' 

你可以使用for循环 :

在*文件中; 做
   回声“$文件”
 DONE

请注意,如果有问题的命令接受多个参数,那么使用xargs几乎总是更有效,因为它只需要一次性生成实用程序而不是多次。

你实际上可以使用sed来做到这一点,只要它是GNU sed。

 ... | sed 's/match/command \0/e' 

怎么运行的:

  1. 用命令匹配replace匹配
  2. 在replace执行命令
  3. 用命令输出replace被replace的行。
 for s in `cmd`; do echo $s; done 

如果cmd的输出很大:

 cmd | xargs -L1 echo 

对我来说效果更好:

 ls -1 | xargs -L1 -d "\n" CMD 

xargs与反斜杠,报价失败。 它需要是类似的东西

 ls -1 |tr \\n \\0 |xargs -0 -iTHIS echo "THIS is a file." 

xargs -0选项:

 -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end of file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. 

ls -1用换行符结束这些项目,所以tr将它们转换成空字符。

这种方法比手动迭代慢50倍左右(见Michael Aaron Safyan的答案)(3.55s vs. 0.066s)。 但对于其他input命令,如定位,查找,从文件( tr \\n \\0 <file )或类似tr \\n \\0 <file读取,您必须像这样使用xargs