-1

I have an xml file :

<record name="rfPathProv">
        <key name="pathId" value="1"/>
        <key name="pathDirection" value="RX"/>
        <field name="band" value="4"/>
</record>
<record name="rfPathProv">
        <key name="pathId" value="1"/>
        <key name="pathDirection" value="TX"/>
        <field name="band" value="4"/>
</record>

I need to replace the band value only if the record name="rfPathProv" and key name="pathId" value="1" using bash scripts. please help. Thanks in advance.

Shilpa
  • 11
  • 1
  • 3
  • Have you tried [parsing the xml](http://stackoverflow.com/questions/893585/how-to-parse-xml-in-bash) and then working from there? – MrAlias Aug 14 '14 at 01:09
  • I did this : sed -i '//,/<\/record>/s/field name="band" value="*"/field name="band" value='\"$bandLte\"'/' $file but i need to know how to check pathId" value="1" before replacing the band value. Kind of stuck here – Shilpa Aug 14 '14 at 01:27
  • please learn to include your attempts to solve your problem with code INTO the body of the question. It should be formatted as you have done with the XML sample. Much easier to read that way. Good luck. – shellter Aug 14 '14 at 02:47

2 Answers2

1

You can try the below, by no means is it perfect at all. In this example I am changing band value to 10.

awk '/<\/record>/{a=0};{
a+=sub(/<record name="rfPathProv">/,"&")
a+=sub(/<key name="pathId" value="1"\/>/,"&")
    if (a==2) {
      sub(/<field name="band" value="[0-9]+"/,"&@")
      sub(/"[0-9]+"@/,"\"10\"")
              }
}1' originalfile > newfile
Ell
  • 927
  • 6
  • 10
  • Hi Ell, The above solution is only printing the updated value on the console but the values are not getting updated in the .xml file. Thanks in Advance. – Shilpa Aug 14 '14 at 16:48
  • Use a redirect to send the output data to a new file. I've updated the code so that it will do this. Just replace the band value obviously, with whatever it should be and the file names. – Ell Aug 14 '14 at 18:32
  • Hi Ell, Thanks for the support. I have posted one more issue. can you please comment. – Shilpa Aug 14 '14 at 19:38
0

This is really an xpath problem. Using xmlstarlet, you can do

xmlstarlet ed -u '//record[@name="rfPathProv" and ./key[@name="pathId" and @value="1"]]/field[@name="band"]/@value' -v 'newValue' file.xml > newfile.xml

output (after providing a top-level node to the sample xml)

<?xml version="1.0"?>
<records>
  <record name="rfPathProv">
    <key name="pathId" value="1"/>
    <key name="pathDirection" value="RX"/>
    <field name="band" value="newValue"/>
  </record>
  <record name="rfPathProv">
    <key name="pathId" value="1"/>
    <key name="pathDirection" value="TX"/>
    <field name="band" value="newValue"/>
  </record>
</records>
glenn jackman
  • 238,783
  • 38
  • 220
  • 352