awk中next和getline的区别

先看下面的几行代码

[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

猜你喜欢

转载自blog.51cto.com/babyshen/2173134