简体   繁体   中英

Sed: delete lines after a pattern for all occurences

I needed some help with sed. I am trying to delete 3 lines after a pattern for all occurrences in a file. 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. Can anyone please help with what am I doing wrong?

I think awk is better for the task. 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):

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. At any time whilst reading these 3 lines, the regexp occurs, reset the count.

If the regexp is also to be deleted, use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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