【问题标题】:how can I "process" text from tee before it is sent to a file如何在将 tee 中的文本发送到文件之前“处理”文本
【发布时间】:2014-04-12 02:23:29
【问题描述】:

有没有办法在将 tee 中的文本发送到文件之前对其进行处理?

例如,如果一个程序输出以下行:

stack 11
stack 22
stack 33
serverfault
serverfault
stack 44

如何仅将包含“堆栈”的行发送到文件,同时仍通过标准输出显示程序的原始输出?

我不确定是否甚至可以使用 tee 来做到这一点,所以我愿意接受任何其他建议。

谢谢

【问题讨论】:

  • cat file && grep stack file > newfile?
  • @BroSlow 抱歉,我在编写原始描述时犯了一个错误,这将用于过滤程序而不是文件的输出

标签: bash shell debian


【解决方案1】:

在终端上显示 myprogram 的完整输出,同时将过滤后的输出保存到文件中:

myprogram | tee /dev/tty | grep stack >out

如果您不想将完整的输出发送到终端,而是想用其他东西处理它,比如someotherprogram,那么我们可以使用 bash 的进程替换:

myprogram | tee >(grep stack >out) | someotherprogram

someotherprogram 在其标准输入上接收myprogram 的完整输出,而只有过滤后的输出保存在out 中。

【讨论】:

  • @KeithReynolds 谢谢。只是为了澄清那些阅读本文的人,您的 tty 始终是 /dev/tty
  • 如何在 tee 的输出 /dev/tty 中保留原始标准输出颜色?
  • @theonlygusti tee /dev/tty 本身不会删除任何颜色。例如,试试echo a b c | grep --color=always b | tee /dev/tty >/dev/null。您应该会看到来自tee /dev/tty 的颜色输出。该问题可能是某些程序可能仅在将输出发送到终端而不是管道时才产生颜色。您可以使用myprogram 的选项来覆盖它。对于grep,该选项为--color=always
  • 我最后使用的解决方案是script -q /dev/null myprogram | tee /dev/tty | someotherprogram
【解决方案2】:

类似于 Keith 的回答,但不依赖任何外部工具(当然除了 tee)

AirBoxOmega:~ d$ man tee|cat > stackHelp.file
AirBoxOmega:~ d$ wc -l stackHelp.file
      33 stackHelp.file
AirBoxOmega:~ d$ cat stackHelp.file|while read i;do if [[ $i =~ "file" ]];then echo "$i"|tee -a stackHelp.out;else echo "$i";fi;done|wc -l
      33
AirBoxOmega:~ d$ grep file stackHelp.out
in zero or more files.  The output is unbuffered.
-a      Append the output to the files rather than overwriting them.
file  A pathname of an output file.
AirBoxOmega:~ d$

您可以将 while 循环放在任何命令之后,然后使用您要查找的任何关键字。在我的示例中,我使用的是 tee 手册页中的文本。

这是打印出来的代码,虽然它相对简单(是的,它是一只无用的猫,但它证明了 while 循环可以读取命令的输出,而不仅仅是从文件中读取)。

cat stackHelp.file | while read i; do
    if [[ $i =~ "file" ]]; then
        echo "$i" | tee -a stackHelp.out;
    else
        echo "$i";
    fi;
done

【讨论】:

    【解决方案3】:

    这不使用 tee,但它会做你想做的一切

    #!/bin/bash
    
    cat |
    while read line ; do 
        echo $line
        echo $line |grep stack >> outfile.txt
    done
    

    【讨论】:

    • 你好,对不起,我在写原始描述时犯了一个错误,这是为了过滤程序而不是文件的输出
    • @lacrosse1991 只需将cat 替换为您正在捕获其输出的程序,或将该程序的输出通过管道传输到此脚本。
    猜你喜欢
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 2012-10-15
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    相关资源
    最近更新 更多