I want to use sed
to replace the XML tag on bash
.
Here is the example xml content for testing:
<xml-content>
<validation>
<timeout>2880</timeout>
<subject>example</subject>
<required>true</required>
</validation>
</xml-content>
I want to replace the tag validation
:
<validation>
<timeout>2880</timeout>
<subject>example</subject>
<required>true</required>
</validation>
with the new tag other-tag
:
<other-tag>
<hello/>
<more>false</more>
</other-tag>
Here is the final expected result:
<xml-content>
<other-tag>
<hello/>
<more>false</more>
</other-tag>
</xml-content>
How to do it with a single command line sed
?
With
sed
you can select all lines in a file between two patterns(including the two lines containingPAT1
andPAT2
) and replace them like so:REPLACEMENT
is text, which has each embedded newline preceded by a backslash.Notice that if
PAT1
orPAT2
contain foreword slashes/
then either each one of them must be escaped with a backslash\/
or the delimiter must be changed to something other than/
and in which case you need to escape the first of each delimiter sequence when thec \
command or any othersed
command is used e.g. you can change the delimiter to_
like so:So you can do:
to edit this:
to this:
Notice that the
sed
s option-i
is needed if you want to edit the original file in place ... Test without it first then use it with a backup suffix e.g.-i.back
to save a backup copy of the original file with.back
extension i.e.file.back
like so:Notice as well that there are tools made especially to edit XML files that you can use to update,delete or insert XML elements ... See How do I replace multiple fields in multiple XML files? as an example ... Those tools however might require a rather more complex command script than what is required for
sed
in some use cases like yours ... I understand why you asked for ased
solution and would myself prefersed
as well over specialized XML tools for such task ... Plussed
would be more portable of course.