【问题标题】:How do I pass output of (both) piped instructions to file?如何将(两个)管道指令的输出传递给文件?
【发布时间】:2016-04-18 14:10:26
【问题描述】:

我有两个命令说 cmd1 和 cmd2,我在其中执行

time cmd1 | cmd2

我想得到类似的东西

cmd1 >> file.out and {time cmd1 >> file.out} | cmd2 >> file.out

所以有人可以建议它实际上是如何完成的吗? 编辑:正如安东尼在下面的回答所暗示的那样, tee 在这里工作,但如果我写了

time cmd1 |tee -a file.out | cmd2 >> file.out

然后它只将 cmd1 的输出写入 file.out,将 cmd2 写入 file.out,而我也希望将 {time cmd1} 的输出写入该文件。

我在 Ubuntu Mate 上使用 bash shell。如果 time 关键字复杂,请提出一些方法来计时执行并进行精确操作。

【问题讨论】:

标签: linux shell stdout pipeline


【解决方案1】:

如果我正确理解您的问题,您希望 cmd 的输出为 写入file.out用作cmd2的输入。对于这种情况,您可以尝试将tee 命令(附加-a 选项)插入到您的命令管道中:

cmd1 | tee -a file.out | cmd2 >> file.out

示例

$ printf "one\ntwo\nthree\n" | tee -a file.out | sed 's/.*/\U&/' >> file.out

$ cat file.out
one
two
three
ONE
TWO
THREE

回答编辑后的问题

下面的构造应该做你想做的事:

{ time cmd1; }  2>> file.out | tee -a file.out | cmd2 >> file.out

由于time utility provided by Bash完整管道上运行,所以group these commands使用大括号,以便将它们视为一个整体。注意:结束分号 (;) 需要在右大括号之前。

cmd1 的标准输出流通过管道传送到 tee 命令,但由于 Bash 的 time 实用程序将其计时统计信息打印到 标准错误,文件描述符 2 被重定向以便将计时统计信息附加到file.out

上例的修改版

{ time printf "one\ntwo\nthree\n"; }  2>> file.out | tee -a file.out | sed 's/.*/\U&/' >> file.out

【讨论】:

  • 这就是我想要的。我找到了关于 tee 但不知道如何一起使用它。让我试试这个:)
  • 虽然有一点点变化。我再次编辑了这个问题。你能帮我解决这个问题吗?
  • @Vivek 这是一个完全不同的问题。使用time 命令会使事情复杂化。我还建议编辑问题以表明您正在使用什么外壳。由于您使用的是 Linux,所以 time 很可能由 Bash shell 作为 shell 关键字 提供。
  • 是的,它是 Ubuntu Mate 上的 bash shell。我现在已经编辑了这个问题。
  • @Vivek 我已经更新了我的答案以回答修改后的问题——尽管您应该在发布之前尽可能完整地描述您的问题。
猜你喜欢
  • 1970-01-01
  • 2014-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多