码迷,mamicode.com
首页 > 其他好文 > 详细

awk中next和getline的区别

时间:2018-09-10 12:04:37      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:reac   执行   系统变量   自己   read   put   exec   字段   man   

先看下面的几行代码

[root@centos ~]# cat a
1 2
3 4
5 6
7 8
[root@centos  ~]# awk ‘{print "$1="$1;getline;print "$2="$2}‘ a
$1=1
$2=4
$1=5
$2=8
[root@centos  ~]# awk ‘{print "$1="$1;next;print "$2="$2}‘ a           
$1=1
$1=3
$1=5
$1=7
 getline是读入下一行,当读取新行后,getline将它赋给$0并将它分解成字段。同时设置系统变量NF,NR,和FNR。因此新行变成当前行,这时可以引用$1并检索第一个字段,引用$2并检索第二个字段。注意前面的行不再看做是变量$0。

而nex就是结束当前行,读取下一行并从第一个规则开始执行脚本。此时下一行还没读入,等待awk自己去读入下一行,这就是getline和next的区别,表面看起来似乎都是读入下一行,其实next不是。

man awk 解释为

getline               Set $0 from next input record; set NF, NR, FNR.
next                  Stop processing the current input record.  The next input record is read and processing starts over with the first pattern in the AWK program.  If the end of the input data is reached, the END block(s), if any, are executed.
[root@centos ~]# cat b
1 2
3 4
5 6
[root@centos ~]# awk ‘{print "$1="$1;getline;print "$2="$2}‘ b
$1=1
$2=4
$1=5
$2=6
这个比较特殊,因为getline失败了,所以$2还是第三行的

[root@centos  ~]# awk ‘{print "$1="$1;next;print "$2="$2}‘ b
$1=1
$1=3
$1=5

awk中next和getline的区别

标签:reac   执行   系统变量   自己   read   put   exec   字段   man   

原文地址:http://blog.51cto.com/babyshen/2173134

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!