Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace 3 lines with another line SED Syntax

Tags:

sed

This is a simple question, I'm not sure if i'm able to do this with sed/awk How can I make sed search for these 3 lines and replace with a line with a determined string?

<Blarg>
<Bllarg>
<Blllarg>

replace with

<test>

I tried with sed "s/<Blarg>\n<Bllarg>\n<Blllarg>/<test>/g" But it just don't seem to find these lines. Probably something with my break line character (?) \n. Am I missing something?

like image 444
ghaschel Avatar asked Mar 10 '26 02:03

ghaschel


2 Answers

Because sed usually handles only one line at a time, your pattern will never match. Try this:

sed '1N;$!N;s/<Blarg>\n<Bllarg>\n<Blllarg>/<test>/;P;D' filename
like image 95
Beta Avatar answered Mar 11 '26 18:03

Beta


This might work for you:

sed '/<Blarg>/ {N;N;s/<Blarg>\n<Bllarg>\n<Blllarg>/<test>/}' <filename>

It works as follows:

  • Search the file till <Blarg> is found
  • Then append the two following lines to the current pattern space using N;N;
  • Check if the current pattern space matches <Blarg>\n<Bllarg>\n<Blllarg>
  • If so, then substitute it with <test>
like image 41
Sicco Avatar answered Mar 11 '26 19:03

Sicco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!