1. 程式人生 > >awk中next和getline的區別

awk中next和getline的區別

next process class cor cut read 開始 Language top

先看下面的幾行代碼

[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

awk中next和getline的區別