1

I have the XML code as follows

<root>
    <list>
        <pair name="id" Value="randomvalue" />
    </list>
    <list>
        <pair name="place" Value="US" />
    </list>
</root>

I need to change the Value(could be any value which we dont know) of the pair tag(whose name attribute is "id") to say "othervalue".

I have tried using: sed -i 's|<pair name="id" Value="[a-zA-Z0-9_]+" />$|<pair name="id" Value="othervalue" />|g' file.xml

But it doesn't work

sai akhil
  • 113
  • 4
  • One problem you're running into, btw, is that in POSIX Basic Regular Expression syntax, which is what `sed` uses by default, `+` is not a special token. – Shawn Aug 02 '21 at 10:06
  • _"How do I edit [...] XML using sed?"_ You don't! You should use an XML parser. – Reino Aug 07 '21 at 22:37

1 Answers1

1

sed, as is almost always the case when it comes to XML, is the wrong thing to use here. Use a tool that understands the format natively, like xmlstarlet. One of its many modes allows you to assign a new value to an attribute or element that matches an XPath expression (Which is a much better and more precise way to match part of an XML document than trying to use regular expressions):

$ xmlstarlet ed -u '/root/list/pair[@name="id"]/@Value' -v othervalue file.xml
<?xml version="1.0"?>
<root>
  <list>
    <pair name="id" Value="othervalue"/>
  </list>
  <list>
    <pair name="place" Value="US"/>
  </list>
</root>

In xmlstarlet ed, -u xpath means "Update the bit that matches the given XPath expression" and -v blah means "With this value".

Add the --inplace option to modify your XML file in-place once you've verified it does the right thing:

xmlstarlet ed --inplace -u '/root/list/pair[@name="id"]/@Value' -v othervalue file.xml
Shawn
  • 47,241
  • 3
  • 26
  • 60
  • Thanks for the answer. Isn't there any other command other than xmlstarlet to solve this? – sai akhil Aug 02 '21 at 10:06
  • 1
    Probably, but xmlstarlet's a very popular choice for working with XML from a script or command line. – Shawn Aug 02 '21 at 10:12