Reputation: 1095
I have a html file which has a table in it as follows:
<td>unknown</td>
<td>blah11</td>
...
<td>unknown</td>
<td>blah24</td>
...
I need to match on 'blah24' and replace the 'unknown' above with 'test' to give:
<td>test</td>
<td>blah24</td>
I have tried to research sed & awk solutions but have only been able to find either 'inserts before the matched pattern' or 'replace after the matched pattern'.
I only have basic shell tools available on a stand alone machine using cygwin.
Upvotes: 0
Views: 1218
Reputation: 11246
In sed you could do
sed -n '/blah24/{x;s/unknown/test/;x};x;1!p;${x;p}' file
<td>unknown</td>
<td>blah11</td>
...
<td>test</td>
<td>blah24</td>
...
Every line it exchanges the current line for the hold buffer. If it finds blah24, then it exchanges the held line, changes it to test, then swaps it back. It prints for every line except 1(as it would print a blank space).
Upvotes: 1
Reputation: 204628
$ awk 'NR>1{if(/blah24/) sub(/unknown/,"test",prev); print prev} {prev=$0} END{print prev}' file
<td>unknown</td>
<td>blah11</td>
...
<td>test</td>
<td>blah24</td>
...
You didn't tell us what to do if blah24
appears as part of a longer string or if you really wanted to specifically replace unknown
or just whatever was within the tags or various other crucial details but hopefully you can figure all that out given the above.
Upvotes: 2