Sed:在匹配前打印 2 行 [英] Sed: print 2 lines before a match
本文介绍了Sed:在匹配前打印 2 行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在文件内匹配之前打印前两行(对于任何匹配)如何制作?
I need to print the two previous lines before matches inside a file (for any match) How to make it?
谢谢
推荐答案
脚本:
sed -n "1N;2N;/XXX[^\n]*$/{h;s/\n[^\n]*$//;p;g};N;D"
工作原理如下:
- 将前三行读入模式空间,
1N;2N
- 在最后一行搜索测试字符串
XXX
,如果找到:在hold spaceh
中保存模式空间,删除最后一行s
,打印p
,然后恢复保存的字符串g
- 将下一行输入追加到模式空间,
N
- 从模式空间中删除第一行并重新启动循环,
D
,注意1N;2N
不再适用
- Read the first three lines into the pattern space,
1N;2N
- Search for the test string
XXX
in the last line, and if found: save pattern space in hold spaceh
, delete last lines
, printp
, and then restore saved stringg
- Append the next line input to pattern space,
N
- Delete first line from pattern space and restart cycle,
D
, noting that1N;2N
is no longer applicable
另见类似SED:在匹配前寻址两行.
这篇关于Sed:在匹配前打印 2 行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文