简体   繁体   English

(g)awk似乎会缓存shell命令的输出-如何避免这种情况?

[英](g)awk seems to cache output of shell commands - how to avoid that?

I have a weird problem with gawk and I don't know if it's a bug or awk's default behavior that I just don't understand. 我对gawk有一个奇怪的问题,我不知道这是我只是不了解的错误还是awk的默认行为。 Basically when I execute a shell command in an awk script and capture its output with getline , all consecutive calls of that command seem to yield the same output as the first one. 基本上,当我在awk脚本中执行shell命令并使用getline捕获其输出时,该命令的所有连续调用似乎都产生与第一个相同的输出。 Here's an example: 这是一个例子:

# <foo.awk 

BEGIN {
  for(i = 0; i < 5; i++) {
    "date +%s" | getline sec
    print sec
    system("sleep 1")
  }
}
# gawk -f foo.awk
1436437519
1436437519
1436437519
1436437519
1436437519
# 

I'd like to know whether this behavior is intentional and explained somewhere in a manual (I couldn't find anything) and if there's a way to work around it. 我想知道这种行为是否是故意的,并在手册的某处进行了说明(我什么都找不到),以及是否有解决方法。

You have to close() the pipe when you are done with each execution of the command: 每次执行命令完成后,都必须关闭管道:

$ cat foo.awk
BEGIN {
  cmd = "date +%s"
  for(i = 0; i < 5; i++) {
    cmd | getline sec
    print sec
    close(cmd)
    system("sleep 1")
  }
}

$ awk -f foo.awk
1436451378
1436451379
1436451380
1436451381
1436451382

Make sure you read and fully understand the sections on getline in the book Effective Awk Programming, 4th Edition, by Arnold Robbins (especially http://www.gnu.org/software/gawk/manual/gawk.html#Getline_002fVariable_002fPipe ) AND fully understand everything at http://awk.info/?tip/getline if you are considering using getline and then usually you'll realize there's a better approach. 确保您已阅读并完全理解Arnold Robbins(特别是http://www.gnu.org/software/gawk/manual/gawk.html#Getline_002fVariable_002fPipe )(有效的Awk编程,第4版,第四版)中的getline部分。如果您正在考虑使用getline,则可以在http://awk.info/?tip/getline上了解所有内容,然后通常会发现有更好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM