【问题标题】:Echo something while piping stdout在管道标准输出时回显某些东西
【发布时间】:2016-03-21 08:41:29
【问题描述】:

我知道如何通过管道输出标准输出:

./myScript | grep 'important'

上述命令的示例输出:

Very important output.
Only important stuff here.

但是在greping 的同时,我还想在每一行添加 echo 一些东西,所以它看起来像这样:

1) Very important output.
2) Only important stuff here.

我该怎么做?

编辑:显然,我没有足够清楚地指定我想要做什么。行数只是一个例子,我一般想知道如何将文本(任何文本,包括变量和诸如此类)添加到管道输出。我看到使用awk '{print $0}' 可以实现这一目标,其中$0 是我正在寻找的解决方案。

还有其他方法可以实现吗?

【问题讨论】:

  • 这与编程无关,但请尝试grep -n 'important'
  • 我在这里做读心术。对于消息,您最好使用stderr 来通知脚本的进度。这不会干扰您正在使用的stdout

标签: bash pipe echo


【解决方案1】:

这将从 0 开始对点击进行编号

./myScript | grep 'important' | awk '{printf("%d) %s\n", NR, $0)}'

1) Very important output.
2) Only important stuff here.

这将为您提供命中的行号

./myScript | grep -n 'important'

3:Very important output.
47:Only important stuff here.

【讨论】:

    【解决方案2】:

    如果您希望新输出上的行号从 1..n 开始运行,其中 n 是新输出中的行数:

    ./myScript | awk '/important/{printf("%d) %s\n", ++i, $0)}'
    #                  ^ Grep part                     ^ Number starting at 1
    

    【讨论】:

      【解决方案3】:

      带有while 循环的解决方案不适合大文件,因此您应该只在没有很多important 东西时使用此解决方案:

      i=0
      while read -r line; do
         ((i++))
         printf "(%s) Look out: %s" $i "${line}"
      done < <(./myScript | grep 'important')
      

      【讨论】:

        猜你喜欢
        • 2014-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-18
        • 1970-01-01
        • 2012-01-25
        相关资源
        最近更新 更多