Home > other >  Update specific value in xml file by bash
Update specific value in xml file by bash

Time:03-22

I need update specific value in xml in automatic way by bash script. My xml file has a lot of similar line like:

<xml>
   <main>
      <buildElement name="test_one" version="" path="" />
      <buildElement name="test_two" version="" path="" />
   </main>
</xml>

I need find element name "test_one" and edit version. I am trying this, but it's not help:

Expected output:

<xml>
   <main>
      <buildElement name="test_one" version="some_value" path="" />
      <buildElement name="test_two" version="" path="" />
   </main>
</xml>

I am trying get this by xmlstarlet and sed, but is not working f.e:

xmlstarlet edit --update '//xml/main/buildElement/name="test_one"/version' --value 'some_value' myXML.xml

CodePudding user response:

Your xpath syntax is incorrect. You need to use @ to refer to attributes, and to search for a particular element you need a filter expression. You want:

xmlstarlet edit --update \
  '//xml/main/buildElement[@name="test_one"]/@version' \
  -v some_value myXML.xml

Which will output:

<?xml version="1.0"?>
<xml>
  <main>
    <buildElement name="test_one" version="some_value" path=""/>
    <buildElement name="test_two" version="" path=""/>
  </main>
</xml>

CodePudding user response:

'//xml/main/buildElement/name="test_one"/version'

You want

'//xml/main/buildElement[@name="test_one"]/@version'

(Basically, you seem to be guessing, and that's not going to get you very far with XPath. Do some reading.)

  • Related