【问题标题】:Redirect only the last line of STDOUT to a file仅将 STDOUT 的最后一行重定向到文件
【发布时间】:2011-01-27 20:53:41
【问题描述】:

我正在编译 Scala 代码并将输出控制台输出写入文件。我只想将 STDOUT 的最后一行保存在文件中。这是命令:

scalac -Xplugin:divbyzero.jar Example.scala >> output.txt

scalac -Xplugin:divbyzero.jar Example.scala 的输出为:

helex@mg:~/git-repositories/my_plugin$ scalac -Xplugin:divbyzero.jar Example.scala | tee -a output.txt
You have overwritten the standard meaning
Literal:()
rhs type: Int(1)
Constant Type: Constant(1)
We have a literal constant
List(localhost.Low)
Constant Type: Constant(1)
Literal:1
rhs type: Int(2)
Constant Type: Constant(2)
We have a literal constant
List(localhost.High)
Constant Type: Constant(2)
Literal:2
rhs type: Boolean(true)
Constant Type: Constant(true)
We have a literal constant
List(localhost.High)
Constant Type: Constant(true)
Literal:true
LEVEL: H
LEVEL: H
okay
LEVEL: H
okay
false
symboltable: Map(a -> 219 | Int | object TestIfConditionWithElseAccept2 | normalTermination | L, c -> 221 | Boolean | object TestIfConditionWithElseAccept2 | normalTermination | H, b -> 220 | Int | object TestIfConditionWithElseAccept2 | normalTermination | H)
pc: Set(L, H)

我只想将 pc: Set(L, H) 保存在输出文件中,而不是其余部分。借助哪个命令可以实现我的目标?

【问题讨论】:

    标签: bash shell unix


    【解决方案1】:

    只需通过tail -n 1 将标准输出通过管道传输到您的文件

    【讨论】:

      【解决方案2】:

      在 Bash 和其他支持进程替换的 shell 中:

      command | tee  >(tail -n 1 > outputfile)
      

      会将完整的输出发送到标准输出,并将输出的最后一行发送到文件。您可以这样做将最后一行附加到文件而不是覆盖它:

      command | tee  >(tail -n 1 >> outputfile)
      

      【讨论】:

        【解决方案3】:

        你可以使用tail:

        scalac -Xplugin:divbyzero.jar Example.scala | tail -1 >> output.txt
        

        【讨论】:

          【解决方案4】:

          这个tail命令的精度很小。如果程序输出标准错误,你必须重定向它

          例子:

          apachectl -t 2>&1 | tail -n 1
          

          重定向:http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-3.html

          【讨论】:

            【解决方案5】:
            scalac ... | awk 'END{print>>"output.txt"}1'
            

            这会将所有内容通过管道传输到标准输出将最后一行附加到 output.txt。

            【讨论】:

            • 这个解决方案的巧妙之处在于它会回显输出并将最后一行发送到输出文件。如果您不关心看到输出:scalac ... | awk 'END{print}' >> output.txt
            • 一般来说,要获取最后一行,tail 是“事实上的”工具,尤其是在文件/输出很大的情况下。在这种情况下,它仍然可以
            猜你喜欢
            • 1970-01-01
            • 2014-07-22
            • 1970-01-01
            • 2019-10-17
            • 2012-05-18
            • 2011-12-28
            • 1970-01-01
            • 2010-10-30
            • 2016-02-19
            相关资源
            最近更新 更多