awk中next和getline的區別

先看下面的幾行代碼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
相關文章
相關標籤/搜索