wael
wael

Reputation: 544

How can I use "sed" to delete 2 lines after match/matches?

I have the following command : sed -i -e '/match1/,+2d' filex, which deletes 2 lines after finding the match "match1" in the file "file x". I want to add several matches to it, like match1, match 2 ....

So it will delete 2 lines after finding any of the matches, how can I achieve this ?

Upvotes: 29

Views: 64074

Answers (3)

Max
Max

Reputation: 341

Not a sed user but it seems to me you could use :

sed -i -e '/(match1|match2)/,+2d' filex

Otherwise you could, if that's possible for you to do, do :

sed -i -e '/match1/,+2d' filex && sed -i -e '/match2/,+2d' filex

EDIT: Looks like I had the right idea but ziu got it.

Upvotes: 14

sehe
sehe

Reputation: 393934

If I understand you correctly, you want

sed -e '/match1/,+2d' input.txt

For example, create input with seq 10 | sed '3i match1' > input.txt:

1
2
match1
3
4
5
6
7
8
9
10

The output of sed -e '/match1/,+2d' input.txt would be:

1
2
5
6
7
8
9
10

Upvotes: 8

ziu
ziu

Reputation: 2720

Two ways, depending upon the sed version and platform:

sed -e '/match1/,+2d' -e '/match2/,+2d' < oldfile > newfile

or

sed -e '/match1\|match2/,+2d' < oldfile > newfile

Upvotes: 39

Related Questions