如何为每个stdin行执行命令? [英] How do I execute command for each stdin line?

查看:37
本文介绍了如何为每个stdin行执行命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下命令:

$ cmd-a | while read -r line; do echo "${line}"; cmd-b; done

这很好用,并且就所有意图和目的而言,看起来 cmd-a 只是正常打印其stdout,但是对于每一行,我们执行 cmd-b 也是

This works well, and will for all intents and purposes look like cmd-a is just printing its stdout as normal, but for each line we execute cmd-b as well.

是否有一种更清洁的方法?

Is there a cleaner way to do this?

cmd-a |xargs -n1 cmd-b 会很好,但是它会在所有空格上分割(我知道GNU xargs具有 -d 选项,但是很不幸,它对我不可用),并且会抑制 cmd-a 的输出.

cmd-a | xargs -n1 cmd-b would be nice, but it splits on all whitespace (I know GNU xargs has the -d option, but it's unfortunately not available to me,) and would suppress the output of cmd-a.

推荐答案

现有提案完全是惯用且干净的; BashFAQ#001 建议完全相同的机制逐行迭代输入.没有理由要更换它,但是如果您经常使用它,则封装它可能很有意义.

The existing proposal is entirely idiomatic and clean; BashFAQ #001 advises precisely the same mechanism to iterate over input line-by-line. There's no reason to replace it, but if you're using it frequently, it may make sense to encapsulate it.

请考虑以下功能:

for_each_line() {
  while IFS= read -r line; do
    printf '%s\n' "$line"
    line=$line "$@"
  done
}

...此后运行为:

cmd-a | for_each_line cmd-b

...或者,如果您的 cmd-b 是一个函数,并且您希望它能够修改shell状态,则可以按以下方式调用以上命令(按

...or, if your cmd-b is a function and you want it to be able to modify shell state, the above can be invoked as follows (per BashFAQ #24):

for_each_line cmd-b < <(cmd-a)

...,如果有任何理由根据相同的值来修改其行为,则它将使环境中的 cmd-b 可以使用上一行.

...which will make the preceding line available to cmd-b in the environment, should it have any reason to modify its behavior based on the value of same.

这篇关于如何为每个stdin行执行命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆