I would like to programmatically update a string in a very simple XML config file, such as this:
<?xml version="1.0"?>
<x>
<z>should be changed</z>
</x>
<y>
<z>should NOT be changed</z>
</y>
Does a simple CLI command exist that will update x/z and NOT y/z ? Perhaps with an XPath selector argument, such as:
$ xml-update myfile.xml /x/z "my new string"
I could write something in Perl or Python, but given the simplicity of this problem, I guess there must be a clever Unix utility that does this already.
Update: I found this but it seems a bit overkill. And I would have to learn XSLT first. http://developerblog.redhat.com/2013/12/05/xml-editing-bash-script/
You can use the xml2/2xml tools to process XML on the command line without too much fuss.
xml2
converts an XML document into a line-oriented format suitable for use with traditional text processing tools likeawk
orsed
, and2xml
takes this format and converts it back to XML.For your example, if I take this document:
Running
xml2
on that content yields:I can modify the content of the
<z>
element like thisI'm using a
sed
search expression to look explicitly for the line starting with/doc/y/z
, and then modifying the content of that line, which gives us:I passed the output through
tidyp
, an XML formatter, because otherwise the document would look like:...which is syntactically correct but harder to read.