![](/img/trans.png)
[英]Print lines between two patterns through sed/AWK when there is at least one line between them
[英]sed : printing lines between two words only when one of the line matches a third word or any pattern
我知道 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
我只想在其中一行包含单词“ALU”时打印两次连续出现的单词“Error”之间的行。
所以我只想打印出以下错误消息:
Error- Undefined port
line1
line2
Undefined port in ALU1
line3
Error- Undefined port
line10
line11
Undefined port in ALU2
line12
为此,您需要在 sed 脚本中进行分支并保持缓冲区。
该脚本使用两个缓冲区:模式缓冲区(它是 sed 存储当前处理的行并用于模式匹配测试的缓冲区)和保持缓冲区(用于存储先前行的缓冲区)。 想法是存储上一次/Error/
模式匹配的所有行,并在下一次/Error/
匹配或 stream 结束时检查/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
order 将模式缓冲区上下文(当前行)与保持缓冲区上下文(上次记住的内容)交换 - 请注意,它将带有 /Error/ 模式的当前行存储到下一次保持缓冲区
H
将当前行上下文附加到保持缓冲区
awk -v RS= -v ORS="\n\n" '/ALU/' 文件
awk 变体:
awk 'BEGIN{RS=ORS="\n\n";FS="\n"}/^Error.+ALU/' file
RS
(记录分隔符)被强制在空白行上
单行返回上的FS
(字段分隔符)
ORS
(输出记录分隔符)设置在 output 的空白行(如果不需要,请删除它)
/^Error.+ALU/
如果记录(文本块)以Error
开头并包含ALU
--> 打印该块。
遗产:
awk '{FS="\n";RS=""} $0 ~ /ALU/ {print $0"\n"}' file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.