Issue
I have a file with the following
<li data-row="1" data-col="2" data-sizex="1" data-sizey="1" class="red">
<article>
<h1>Some unique text</h1>
<li data-row="1" data-col="3" data-sizex="1" data-sizey="1" class="red">
<article>
<h1>More unique text</h1>
<li data-row="1" data-col="3" data-sizex="1" data-sizey="1" class="red">
<article>
<h1>Even more unique text</h1>
I need to be able change the colour value before a specific string i.e
search for "More unique text" and replace the colour red to orange so the output is
<li data-row="1" data-col="3" data-sizex="1" data-sizey="1" class="orange">
<article>
<h1>More unique text</h1>
and the other colour values are left as red.
I can get the colour in the line i want to change using
grep -B 2 "More unique text" file | sed -e '2,4d'
which returns
<li data-row="1" data-col="3" data-sizex="1" data-sizey="1" class="red">
But how do i change the value red to orange?
Solution
xml parser like xmlstarlet
is better suited to parse xml/html. If your input strictly follows the rules mentioned in your question, you can use
perl -i -0777 -pe 's/class="\Kred(?=".*\n.*\n.*More unique text)/orange/'
-i
for inplace editing-0777
to slurp entire input as single string, so this isn't suited for large input filesclass="\K
matchclass="
but don't include it as part of matched textred
text to match(?=".*\n.*\n.*More unique text)
match"
and check ifMore unique text
is present two lines ahead(?=regexp)
is a lookahead feature, won't be part of matched text
Answered By - Sundeep