+ -
当前位置:首页 → 问答吧 → 求解释awk getline的用法

求解释awk getline的用法

时间:2011-06-20

来源:互联网

本帖最后由 liion631818 于 2011-06-20 16:51 编辑
  1. cat file
  2. 1
  3. 2
  4. 3
  5. 4
  6. awk '{"echo ok" | getline; print}' file
  7. ok
  8. 2
  9. 3
  10. 4
复制代码
为什么结果不是
  1. ok
  2. ok
  3. ok
  4. ok
复制代码
可以肯定 "echo ok" | getline 只执行了一次,可以通过下面的代码证明:
  1. awk 'BEGIN{while("echo ok" | getline) print ++i}'
  2. 1
复制代码
why???

如果管道前面命令输出有多行,getline就执行失败了,下面的代码变量 i 没有被打印出来
  1. awk 'BEGIN{while("time" | getline)print ++i}'
  2. real    0m0.000s
  3. user    0m0.000s
  4. sys     0m0.000s
复制代码
why???

例外,shell中管道2边会fork出新的进程,在awk中怎样理解?

作者: liion631818   发布时间: 2011-06-20

  1. $ awk 'BEGIN{while("ls -1" | getline)print ++i}'
  2. 1
  3. 2
  4. 3
  5. 4
  6. 5
  7. 6
复制代码
想了下,管道就相当指定了getline从某个地方去数据,所以上面描述的现象都是正确的,
while("echo ok" | getline), echo只输出了一行,所以getline只运行正常了一次,不是我之前理解的每次循环"echo ok" | getline 都执行一次,而是getline每次都执行,而echo ok只执行一次。

就是不知道上面的time命令怎么没跟ls一样正确执行了,这点求高手解释。??

写了这么多,耽误大家时间了


QUOTE:
When the output of a command is piped to getline and it contains multiple lines, getline reads a
line at a time. The first time getline is called it reads the first line of output. If you call it again, it
reads the second line. To read all the lines of output, you must set up a loop that executes getline
until there is no more output. For instance, the following example uses a while loop to read each line
of output and assign it to the next element of the array, who_out:
while ("who" | getline)
who_out[++i] = $0
Each time the getline function is called, it reads the next line of output. The who command,
however, is executed only once.

作者: liion631818   发布时间: 2011-06-20

本帖最后由 lionfun 于 2011-06-20 18:47 编辑

回复 liion631818


   我觉得与time的这个命令的特殊性有关!题目中的time命令应该是bash的builtin命令!
   time的输出是stderr,其直接在当前主shell中执行,这个time命令特殊的地方就是对命令的重定向无法在当前shell环境完成
  将这个time命令放入subshell执行:
  1. [root@station3 ~]# awk 'BEGIN{while("(time;)2>&1" | getline)print ++i}'
  2. 1
  3. 2
  4. 3
  5. 4
复制代码
如果是非bash的builtin命令,即/usr/bin/time,就可以重定向:
  1. [root@station3 ~]# /usr/bin/time -p pwd 2>&1 1>/dev/null
  2. real 0.00
  3. user 0.00
  4. sys 0.00
  5. [root@station3 ~]# awk 'BEGIN{while("/usr/bin/time -p pwd 2>&1 1>/dev/null" | getline)print ++i}'
  6. 1
  7. 2
  8. 3
复制代码

作者: lionfun   发布时间: 2011-06-20