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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章