如何在 bash 中将输出作为命令行参数传递?

How to pass output as command line argument in bash?

我有这两步 bash 命令:

L=`wc -l testfile | cut -d' ' -f1`
myprogram testfile $L testfile.out

长话短说,myprogram 需要行数作为输入。

我想把它合并成一行

工作,因为使用重定向 |- 将 stdout 流作为文件而不是字符串传递。

wc -l testfile | cut -d' ' -f1 | myprogram testfile - testfile.out

有没有办法将其合并为一行?

使用进程替换:

myprogram testfile $(wc -l < testfile) testfile.out
                   ^^^^^^^^^^^^^^^^^^^

这样,wc -l < testfile 与程序调用一起计算,并且您将两个命令组合在一起。

注意 wc -l < file returns 你只是数字,所以你不必做 cut 或任何其他事情来清理输出。