其他分享
首页 > 其他分享> > awk之getline函数与next语句

awk之getline函数与next语句

作者:互联网

1、准备测试内容

# cat test1.txt
plans are living things.
plans need sun, air and water
i like to read and draw
how many box are there

2、next 开始输入主循环的下一次迭代

# awk '{print "before next statement NR is:", NR} /plans/{next;print $0} {print  NR, $0 }' test1.txt
before next statement NR is: 1
before next statement NR is: 2
before next statement NR is: 3
3 i like to read and draw
before next statement NR is: 4
4 how many box are there

文本第一行匹配/plans/ 执行到next, 跳过了next 后面语句的执行,直接开始下一行的迭代;

同理,文本第二行也是, 都未执行next 后续所有的语句

文本第三行和第四行未匹配到/plans/, 没有执行next,所以打印了记录号和$0

3、函数 getline 可以从当前输入行, 或文件, 或管道, 读取输入. getline 抓取下一个记录, 按照通
常的方式把记录分割成一个个的字段. 它会设置 NF, NR, 和 FNR; 如果存在一个记录, 返回 1, 若遇到文件末尾, 返回 0, 发生错误时返回 -1 (例如打开文件失败).
 

getline函数
表达式被设置的变量
getline$0, NF, NR, FNR
getline varvar, NR, FNR
getline < file$0, NF
getline var <filevar
cmd | getline$0, NF
cmd | getline varvar
# awk '/plans/{getline ;print NR , "getline", $0} {print  NR,"normal", $0}' test1.txt
2 getline plans need sun, air and water  # $0 变了
2 normal plans need sun, air and water
3 normal i like to read and draw
4 normal how many box are there

# awk '/plans/{getline x;print NR , "getline", $0} {print  NR,"normal", $0}' test1.txt
2 getline plans are living things.   # $0 没变
2 normal plans are living things.
3 normal i like to read and draw
4 normal how many box are there

awk提取文本第一行,此时NR为1,匹配/plans/ 执行到getline, 提取了下一个记录(第二行),此时NR 变量增1,变为2, getline后面的语句会正常执行;下一个循环,awk提取第三行进行处理

标签:plans,normal,next,awk,print,NR,getline
来源: https://blog.csdn.net/Wanhuake/article/details/122379979