ghaschel
ghaschel

Reputation: 1355

Replace 3 lines with another line SED Syntax

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?

Upvotes: 3

Views: 3837

Answers (3)

ceving
ceving

Reputation: 23866

You can use range addresses with regular expressions an the c command, which does exactly what you are asking for:

sed '/<Blarg>/,/<Blllarg>/c<test>' filename

Upvotes: 0

Sicco
Sicco

Reputation: 6271

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>

Upvotes: 3

Beta
Beta

Reputation: 99124

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

Upvotes: 5

Related Questions