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

转载于:https://blog.51cto.com/babyshen/2173134

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值