将标准输出作为命令行工具的文件名传递? [英] pass stdout as file name for command line util?
问题描述
我正在使用一个命令行实用程序,它需要传递文件名以将输出写入,例如
I'm working with a command line utility that requires passing the name of a file to write output to, e.g.
foo -o output.txt
它写入stdout
的唯一内容是一条消息,表明它已成功运行.我希望能够将写入 output.txt
的所有内容通过管道传输到另一个命令行实用程序.我的动机是 output.txt 最终将成为我不需要保留的 40 GB 文件,我宁愿通过管道传输流,也不愿逐步处理大量文件.
The only thing it writes to stdout
is a message that indicates that it ran successfully. I'd like to be able to pipe everything that is written to output.txt
to another command line utility. My motivation is that output.txt will end up being a 40 GB file that I don't need to keep, and I'd rather pipe the streams than work on massive files in a stepwise manner.
在这种情况下,有什么方法可以将实际输出(即 output.txt
)通过管道传输到另一个命令?我可以以某种方式神奇地将 stdout
作为文件参数传递吗?
Is there any way in this scenario to pipe the real output (i.e. output.txt
) to another command? Can I somehow magically pass stdout
as the file argument?
推荐答案
解决方案 1:使用 进程替换>
最方便的方法是使用进程替换.在 bash 中,语法如下所示:
Solution 1: Using process substitution
The most convenient way of doing this is by using process substitution. In bash the syntax looks as follows:
foo -o >(other_command)
(请注意,这是一个 bashism.其他 shell 也有类似的解决方案,但最重要的是它不可移植.)
(Note that this is a bashism. There's similar solutions for other shells, but bottom line is that it's not portable.)
您可以按如下方式显式/手动执行上述操作:
You can do the above explicitly / manually as follows:
使用
mkfifo
命令创建命名管道.
mkfifo my_buf
使用该文件作为输入启动其他命令
Launch your other command with that file as input
other_command < my_buf
执行 foo
并让它将输出写入 my_buf
foo -o my_buf
解决方案 3:使用 /dev/stdout
你也可以使用设备文件/dev/stdout
如下
foo -o /dev/stdout | other_command
这篇关于将标准输出作为命令行工具的文件名传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!