简体   繁体   English

Sed:删除所有出现的模式后的行

[英]Sed: delete lines after a pattern for all occurences

I needed some help with sed. 我需要sed的帮助。 I am trying to delete 3 lines after a pattern for all occurrences in a file. 我正在尝试删除文件中所有出现的模式后的3行。 I do 我做

sed '/pattern/,+3d' file.

This only deletes 3 lines and the pattern for the first occurrence but just deletes the pattern for the second occurrence but not the lines after which is really confusing. 这只会删除3行和第一次出现的模式,但只会删除第二次出现的模式,但不会删除之后的行,这确实令人困惑。 Can anyone please help with what am I doing wrong? 谁能帮我解决我的错?

I think awk is better for the task. 我认为awk更好地完成了任务。 For example, 例如,

$ cat file
1
2
4
a0
1
a1
1
2
3
4
5

Run

awk '
flag   { i ++            }
i == 3 { flag = 0        }
!flag
/a/    { flag = 1; i = 0 }
' file

Output 产量

1
2
4
a0
3
4
5

This might work for you (GNU sed): 这可能对您有用(GNU sed):

sed -n '/regexp/{p;:a;n;//ba;n;//ba;n;//ba;d};p' file

If the regexp is encountered, print the current line and then delete the following 3 lines. 如果遇到正则表达式,请打印当前行,然后删除以下3行。 At any time whilst reading these 3 lines, the regexp occurs, reset the count. 在读取这3行的任何时候,都会发生正则表达式,请重置计数。

If the regexp is also to be deleted, use: 如果正则表达式也要删除,请使用:

sed -n '/regexp/{:a;n;//ba;n;//ba;n;//ba;d};p' file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM