linux – sed:只有当其中一行匹配第三个单词或任何模式时,才会
发布时间:2020-12-13 23:49:47 所属栏目:Linux 来源:网络整理
导读:我知道sed使用以下命令从test.txt打印单词FOO和BAR之间的行 sed -n '/FOO/,/BAR/p' test.txt 但是,只有当其中一条线具有匹配的图案时,我如何使sed打印FOO和BAR之间的线条 例如,文件text.txt包含以下行: Error- Undefined portline1line2Undefined port in A
我知道sed使用以下命令从test.txt打印单词FOO和BAR之间的行
sed -n '/FOO/,/BAR/p' test.txt 但是,只有当其中一条线具有匹配的图案时,我如何使sed打印FOO和BAR之间的线条 例如,文件text.txt包含以下行: Error- Undefined port line1 line2 Undefined port in ALU1 line3 Error- Undefined port line4 line5 Undefined port in LSU line6 Error- Undefined port line7 line8 Undefined port in FGU line9 Error- Undefined port line10 line11 Undefined port in ALU2 line12 我想在两次连续出现之间打印出行 所以我只想打印出以下错误消息: Error- Undefined port line1 line2 Undefined port in ALU1 line3 Error- Undefined port line10 line11 Undefined port in ALU2 line12 解决方法
要实现这一点,您需要在sed脚本中分支并保留缓冲区.
该脚本使用两个缓冲区:模式缓冲区(它是sed存储当前处理的行的缓冲区,用于模式匹配测试的缓冲区)和保持缓冲区(用于存储前一行的缓冲区).我们的想法是存储上一个/错误/模式匹配的所有行,并在下一个/错误/匹配或流结束时检查/ ALU /出现. sed -n ' # if /Error/ pattern occured,jump to /ALU/ check /Error/ b alu_check # else append current line to the hold buffer H # if the current line is the last one,jump to /ALU/ check $b alu_check # otherwise jump to end of script (= finish processing of this line) b # alu_check: :alu_check # exchange current pattern buffer with hols buffer context x # print previous record if /ALU/ occured /ALU/ p ' x命令用保持缓冲区上下文(从上次记住的内容)交换模式缓冲区上下文(当前行) – 注意它将当前行/ Error / pattern存储到保持缓冲区以供下次使用 H将当前行上下文附加到保持缓冲区 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |