linux awk 命令中 next 和 getline
001、 continue
[root@PC1 test01]# ls data [root@PC1 test01]# cat data ## 测试数据 1000 naughty 500 cc 400 zoer 100 [root@PC1 test01]# awk '{if(NR == 2) {next}; print $0}' data ## next相当于外层循环的continue,表示跳过该次迭代 1000 cc 400 zoer 100 [root@PC1 test01]# awk '{if(NR == 2) {printf("")}; print $0}' data ## 分号后面的print $0是对整个文件起作用的,说明上面的next语句跳过NR == 2 1000 naughty 500 cc 400 zoer 100
002、getline
[root@PC1 test01]# ls a.txt [root@PC1 test01]# cat a.txt ## 测试数据 1 Bob male 28 abc@qq.com 18023394012 2 Alice female 24 def@gmail.com 18084925203 3 Alice female 24 def@gmail.com 18084925203 10 Bruce female 27 bcbd@139.com 13942943905 10 Bruce female 27 bcbd@139.com 1394294390_002_5 [root@PC1 test01]# awk '/^1/{print $0; getline; print $0 }' a.txt ## getline表示跳到下一行,同时具有一次print 的机会 1 Bob male 28 abc@qq.com 18023394012 2 Alice female 24 def@gmail.com 18084925203 10 Bruce female 27 bcbd@139.com 13942943905 10 Bruce female 27 bcbd@139.com 1394294390_002_5 [root@PC1 test01]# awk '/^1/{print $0; getline; print "xxx" }' a.txt ## 没有打印第二个以10开头的行,说明getline跳过了改行 1 Bob male 28 abc@qq.com 18023394012 xxx 10 Bruce female 27 bcbd@139.com 13942943905 xxx
003、next的情况
[root@PC1 test01]# ls a.txt [root@PC1 test01]# cat a.txt ## 测试数据 1 Bob male 28 abc@qq.com 18023394012 2 Alice female 24 def@gmail.com 18084925203 3 Alice female 24 def@gmail.com 18084925203 10 Bruce female 27 bcbd@139.com 13942943905 10 Bruce female 27 bcbd@139.com 1394294390_002_5 [root@PC1 test01]# awk '/^1/{print $0; next; print $0 }' a.txt ## next命令跳过外层循环 1 Bob male 28 abc@qq.com 18023394012 10 Bruce female 27 bcbd@139.com 13942943905 10 Bruce female 27 bcbd@139.com 1394294390_002_5 [root@PC1 test01]# awk '/^1/{print $0; next; print "xxx" }' a.txt ## next跳过外层循环,不再执行后面的程序 1 Bob male 28 abc@qq.com 18023394012 10 Bruce female 27 bcbd@139.com 13942943905 10 Bruce female 27 bcbd@139.com 1394294390_002_5
004、getline
[root@PC1 test01]# ls a.txt [root@PC1 test01]# cat a.txt 1 Bob male 28 abc@qq.com 18023394012 2 Alice female 24 def@gmail.com 18084925203 3 Alice female 24 def@gmail.com 18084925203 4 Alice female 24 def@gmail.com 18084925203 10 Bruce female 27 bcbd@139.com 13942943905 10 Bruce female 27 bcbd@139.com 1394294390_002_5 [root@PC1 test01]# awk '/^1/{print $0; getline; getline; print $0 }' a.txt ## 两个getline同时使用,处理匹配行后面的第二行 1 Bob male 28 abc@qq.com 18023394012 3 Alice female 24 def@gmail.com 18084925203 10 Bruce female 27 bcbd@139.com 13942943905 10 Bruce female 27 bcbd@139.com 1394294390_002_5 [root@PC1 test01]# awk '/^1/{print $0; getline; getline; print "xxx" }' a.txt 1 Bob male 28 abc@qq.com 18023394012 xxx 10 Bruce female 27 bcbd@139.com 13942943905 xxx [root@PC1 test01]# awk '/^1/{print $0; getline; getline; print NR, "xxx" }' a.txt ## 同时输出行号 1 Bob male 28 abc@qq.com 18023394012 3 xxx 10 Bruce female 27 bcbd@139.com 13942943905 6 xxx
。
参考:https://www.likecs.com/show-307069191.html