0

I am trying to edit the XML file using sed. Here is the file content which I am trying to edit.

<configuration key="student1">
   <list>
     <value>abc</value>
     <value>def</value>
   </list>
</configuration>

I want to add the following value to the existing node by comparing the key value.

<configuration key="student1">
    <list>
      <value>abc</value>
      <value>NEWVALUE</value>
      <value>def</value>
    </list>
</configuration>

How can I achieve it using the sed command? After going to lot of posts, xmlstarlet is the best one to edit the xml files. but I am not able to install due to permission issue. Can someone help me for the solution?

Update:

What I have tried is :

sed -i "s/\<\list\>/ \<value\> NEWVALUE\<\/VALUE\>/" xmlfile

This is not working as expected, its replacing the list tag with the NEWVALUE. But I need to compare the key value, then traverse through the lists, then add the new value.

  • add the sed code you tried... SO is about helping you with code you already tried and got stuck... – Sundeep Jul 05 '17 at 13:32
  • There's likely to be a way to install whatever you want in your home directory. Sed (or any other text processing program) is definitely not the right tool for the job. – Tom Fenech Jul 05 '17 at 13:48
  • @Sundeep, I have added the code which I tried. – Basil Jose Jul 06 '17 at 06:39
  • @BasilJose what you tried is nowhere close to what you want.. you are simply trying to replace `` tag.. and `\<` and `\>` having special meaning of matching word boundaries in GNU sed... what is the key value you want to compare? `student1` or `abc`? in any case, using `sed` here is really not the best idea – Sundeep Jul 06 '17 at 06:56

1 Answers1

1

If you are desperate and the order of the values isn't important you could use sed and insert the value before the closing list tag and so:

sed -r '/\<\list\>/ i\ \t<value>NEWVAL</value>' xmlfile

Search the the closing list tag and then enter the value tags along with the NEWVAL value.

Raman Sailopal
  • 12,320
  • 2
  • 11
  • 18