查找特定的图案并使用awk或sed打印完整的文本块 [英] Find specific pattern and print complete text block using awk or sed
问题描述
如何在文本块中找到特定的数字并打印以关键字"BEGIN"
开始并以"END"
结尾的 complete 文本块?基本上,这就是我的文件的样子:
How can find a specific number in a text block and print the complete text block beginning with the key word "BEGIN"
and ending with "END"
? Basically this is what my file looks like:
BEGIN
A: abc
B: 12345
C: def
END
BEGIN
A: xyz
B: 56789
C: abc
END
BEGIN
A: ghi
B: 56712
C: pqr
END
[...]
如果我正在寻找'^B: 567'
,我想获得以下输出:
If I was looking for '^B: 567'
, I would like to get this output:
BEGIN
A: xyz
B: 56789
C: abc
END
BEGIN
A: ghi
B: 56712
C: pqr
END
我可以在这里使用grep( grep -E -B2 -A2 "^B: 567" file
),但我想获得更通用的解决方案.我猜 awk 或 sed 也许可以做到这一点!?
I could use grep here (grep -E -B2 -A2 "^B: 567" file
), but I would like to get a more general solution. I guess awk or sed might be able to do this!?
谢谢! :)
推荐答案
$ awk -v RS= -v ORS='\n\n' '/\nB: 567/' file
BEGIN
A: xyz
B: 56789
C: abc
END
BEGIN
A: ghi
B: 56712
C: pqr
END
请注意在B
之前的\n
以确保它出现在行的开头,这代替了您最初使用的^
字符串开始字符,因为现在每行都不是自己的细绳.您需要在上面设置ORS,以便在记录之间重新插入空白行.
Note the \n
before B
to ensure it occurs at the start of a line.This is in place of the ^
start-of-string character you had originally since now each line isn't it's own string. You need to set ORS above to re-insert the blank line between records.
这篇关于查找特定的图案并使用awk或sed打印完整的文本块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!