I need to search an xml file for some text that resides within a start/end tag and if found, to write a line of text just before the end tag.
Eg, in the XML file I need to search MyTag for “MyText1”. If found, add FoundIt right before the end tag as shown below
<MyTag>
<Tag1>MyText1</Tag1>
<Tag2>MyText2</Tag2>
<Tag3>MyText3</Tag3>
<Tag4>MyText4</Tag4>
<FoundTag1>FoundIt</FoundTag1>
</MyTag>
I was able to use sed to search for the range and print MyText1. But what I really want to be able to do is add the “FoundIt” tag right before the end tag.
Sed Script
/<MyTag>/,/</MyTag>/{
/<Tag1>MyText1</Tag1>/p
}
XML File Contents
<XmlFile>
<BeginTag>
<SomeTag>Text</SomeTag>
</BegingTag>
<MyTag>
<Tag1>MyText1</Tag1>
<Tag2>MyText2</Tag2>
<Tag3>MyText3</Tag3>
<Tag4>MyText4</Tag4>
</MyTag>
<EndTag>
<SomeTag>Text</SomeTag>
</EndTag>
</XmlFile>
1
This might work for you (GNU sed):
sed '/<MyTag>/!b;:a;/</MyTag>/!{$!{N;ba}};/MyText1/s/.*n/&<FoundTag1>FoundIt</FoundTag1>n/' xml_file
Look for a line containing <MyTag>
if not bail out. Once found, collect lines until the line </MyTag>
occurs, then check if those lines contain MyText1
and if so substitute <FoundTag1>FoundIt</FoundTag1>
followed by a new line before the last line collected.
2
You can try this:
sed -n '
/<MyTag>/,/</MyTag>/!{p;};
/<MyTag>/,/</MyTag>/{H;};
/</MyTag>/{s/.*//;x;};
/.*MyText1.*/{s/</MyTag>/<FoundTag1>FoundIt</FoundTag1>n&/;};
/</MyTag>/{p;};
'
xml_file
1