将 awk 的 print/printf 输出传送到 shell 命令中,使该语句在所有其他不相关的 print/printf 语句之后运行

Ask*_*321 5 pipe awk

鉴于此awk脚本:

END  {
print "Y" | "cat" 

print "X"
print "X"
}

# Output: 
# X
# X
# Y
Run Code Online (Sandbox Code Playgroud)

既然 Y 应该在其他语句之前运行,为什么不首先打印它?

gue*_*est 5

如果您希望cat进程YXs之前终止(并且要打印),那么只需close("cat")print "Y" | "cat".

其余所有内容都在手册页中进行了解释,您最好阅读一下。

既然 Y 应该在其他语句之前运行,为什么不首先打印它?

cat不应该写它的输出,另一个语句之前终止。它可能会在两次print "X"调用之前、之后或之间写入其输出。

当您print ... | "command ..."在 awk 中使用类似的东西时,command ..它作为一个异步进程启动,其标准输入连接到管道(via popen("command ...", "w")),并且该进程不一定会在您调用之前终止并写入其输出close("command ...")(或者在 awk 终止时隐式完成)。

看一个例子:

BEGIN {
   print "foo" | "cat > file"
   print "bar" | "cat > file"
}
Run Code Online (Sandbox Code Playgroud)

结果将file包含两行,foobar; 该cat > file命令不会为每一行单独运行。