Edit xml file using shell script / command

bashbash-scriptingshellshell-scriptunix

I need to do this using unix script or command
There is a xml file in /home/user/app/xmlfiles like

<book>
   <fiction type='a'>
      <author type=''></author>
   </fiction>
   <fiction type='b'>
      <author type=''></author>
   </fiction>
   <Romance>
       <author type=''></author>
   </Romance>
</book>

I want to edit author type in fiction as local .

   <fiction>
      <author type='Local'></author>
   </fiction>

I need to change the author type which is in fiction tag with attribute b alone.
Please help me with this using unix shell script or command. Thanks !

Best Answer

If you just want to replace <author type=''><\/author> with <author type='Local'><\/author>, you can use that sed command:

sed "/<fiction type='a'>/,/<\/fiction>/ s/<author type=''><\/author>/<author type='Local'><\/author>/g;" file

But, when dealing with xml, I recommend an xml parser/editor like xmlstarlet:

$ xmlstarlet ed -u /book/*/author[@type]/@type -v "Local"  file
<?xml version="1.0"?>
<book>
  <fiction>
    <author type="Local"/>
  </fiction>
  <Romance>
    <author type="Local"/>
  </Romance>
</book>

Use the -L flag to edit the file inline, instead to printing the changes.

Related Question