Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 ?

like image 587
wael Avatar asked Nov 30 '11 08:11

wael


People also ask

How do I delete a sed matching line?

To begin with, if you want to delete a line containing the keyword, you would run sed as shown below. Similarly, you could run the sed command with option -n and negated p , (! p) command. To delete lines containing multiple keywords, for example to delete lines with the keyword green or lines with keyword violet.

Which option from sed command is used to delete 2nd line in a file?

To delete a line, we'll use the sed “d” command. Note that you have to declare which line to delete. Otherwise, sed will delete all the lines.


2 Answers

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 
like image 110
ziu Avatar answered Sep 21 '22 02:09

ziu


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.

like image 36
Max Avatar answered Sep 22 '22 02:09

Max