我知道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- Undefined port
line1
line2
Undefined port in ALU1
line3
Error- Undefined port
line10
line11
Undefined port in ALU2
line12
要实现这一点,您需要在sed脚本和hold缓冲区中进行分支。
脚本使用两个缓冲区:模式缓冲区(它是sed存储当前处理的行的缓冲区,用于模式匹配测试)和保持缓冲区(用于存储以前的行的缓冲器)。其思想是存储来自上一次/Error/
模式匹配的所有行,并在下一次/Error/
匹配或流结束时检查/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/模式的当前行存储到下一次的保持缓冲中
H
将当前行上下文附加到保持缓冲区
awk变体:
awk 'BEGIN{RS=ORS="nn";FS="n"}/^Error.+ALU/' file
在空白行上强制使用RS
(记录分隔符)
单线返回上的FS
(字段分离器)
ORS
(输出记录分隔符)设置在输出的空行上(如果不需要,请删除它)
/^Error.+ALU/
如果记录(文本块)以Error
开始并包含ALU
-->则打印该块。
awk-v RS=-v ORS="\n\n"'/ALU/'文件
遗留:
awk '{FS="n";RS=""} $0 ~ /ALU/ {print $0"n"}' file