删除所有行,在/pattern/之后的两行开始 [英] Delete all lines, starting two lines after /pattern/
问题描述
想象一下我有一个文件,以下文件:
Imagine I have a file the following file:
drink
eat
XXX
pizza
blunzn
sushi
我想从文件中删除所有行,从模式 XXX
之后的第三行开始,因此结果应类似于:
I would like to remove all lines from the file, starting with the third line after the pattern XXX
, so the result should look like:
drink
eat
XXX
pizza
blunzn
删除 XXX
之后的所有行非常简单:
Removing all lines after XXX
is simple enough:
sed -e '/XXX/q' -i data.txt
但是,我发现删除模式后很难跳过固定数量的行.
However, I find it hard to skip a fixed number of lines after the pattern from deletion.
到目前为止,我想到的最好的方法是:
The best I came up with so far is:
sed -e '/XXX/ { N; N; q }' -i data.txt
有什么比添加n * N
更优雅的了(想象中,我想跳过50行)?
Is there something more elegant, than adding n * N
(imagine, I would like to skip 50 lines)??
推荐答案
这可能对您有用(GNU sed):
This might work for you (GNU sed):
sed '/pattern/{:a;N;s/\n/&/2;Ta;q}' file
遇到所需的模式时,循环所需的行,然后退出.
On encountering the required pattern, loop the required lines then quit.
对于遵循所需模式的五十行,请使用:
For fifty lines following the required pattern, use:
sed '/pattern/{:a;N;s/\n/&/50;Ta;q}' file
这篇关于删除所有行,在/pattern/之后的两行开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!