Home > Enterprise >  Sed command to replace a text with line breaks (multiple lines)
Sed command to replace a text with line breaks (multiple lines)

Time:05-27

I want to replace values in a html file using a shell script. I am trying to do this using sed commands.

Here I have the text part 01 -->

<tr><th>Text</th>
</tr> 

Here you can see tag is after a line break.

I want to replace this with the text part 02 --->

<tr><th>Text</th>
<td>No applications>
</tr> 

Here also you can see line breaks.

I want to replace those 2 text parts with a sed command by assigning these 2 text parts to two variables

sed -i -e "s|$var1|$var2|g" mypage.html

this gives an error saying "no previous regular expression" I think the reason is the texts are having the line breaks. I cannot avoid these line breaks because values are returned to the html table row by a loop ex - <tr> loop here </tr>

I want to replace only if the loop is null. it means there is nothing between tags.

So is there any ideas how to do this. Thanks in advance.

CodePudding user response:

So is there any ideas how to do this.

I was able to devise scheme to do replace

<tr><th>Text</th>
</tr>

using

<tr><th>Text</th>
<td>No applications>
</tr>

via GNU sed which is as follows, let file.txt content be

<tr><th>Text</th>
</tr>
something else
<tr><th>Text</th>
</tr>

then

sed -e '1{h;d}' -e '$!{H;d}' -e '${H;g;s|<tr><th>Text</th>\n</tr>|<tr><th>Text</th>\n<td>No applications>\n</tr>|g}' file.txt

output

<tr><th>Text</th>
<td>No applications>
</tr>
something else
<tr><th>Text</th>
<td>No applications>
</tr>

Explanation: I exploit feature dubbed hold space of GNU sed. I instruct GNU sed to

  • for 1st line copy current line to hold (h) and go to next line (d)
  • for all but last line append newline and current line to hold (H) and to go next line (d)
  • for last line append newline and current line to hold (H) then set current line content to what is in hold (g) then globally replaces text for text as specified.

(tested in GNU sed 4.2.2)

CodePudding user response:

This might work for you (GNU sed):

sed '/^<tr><th>Text<\/th>$/!b;n;/^<\`/tr>$/i\<td>No applications>' file

If the current line is not <tr><th>Text</th> then bail out.

Otherwise, print the current line and fetch the next line and if that line is </tr> then insert <td>No applications>.

  • Related