ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

awk之getline函数与next语句

2022-01-08 14:58:43  阅读:176  来源: 互联网

标签:plans normal next awk print NR getline


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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有