先看下面的几行代码centos
[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 解释为bash
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