Friday, April 15, 2022

[SOLVED] Replace multiple lines by one line starting from the next line of the occurrence

Issue

I want to replace multiple lines starting from the next line of the occurrence by one line.

For example, I have the following section of an html file:

...
<div class="myclass">
  <p textselect="true">
     one
     two
     three
  </p>
</div>
...

I want to end up with

...
<div class="myclass">
  <p textselect="true">
     hello
  </p>
</div>
...

...but I need to be able to match the string with <p textselect="true">, rather then with one, as I don't know what that string (one) is going to be.

Right now my solution is pretty nasty. I am appending a placeholder after <div class="myclass">, I delete the placeholder and the next 3 lines, then I append again the string I want. All with sed. I need it to be either with sed or awk.


Solution

This might work for you (GNU sed):

sed -E '/<p textselect="true">/{:a;N;/<\/p>/!ba;s/(\n\s*).*\n/\1hello\n/}' file

Gather up lines between <p textselect="true"> and </p> and replace the string inbetween with hello.

Alternative:

sed -n '/<p textselect="true">/{p;n;s/\S\+/hello/;h;:a;n;/<\/p>/!ba;H;g};p' file

N.B. Both solutions expect at least one line to be replaced.



Answered By - potong
Answer Checked By - Cary Denson (WPSolving Admin)