Edit xml file using shell script / command

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.


xmlstarlet edit --update "/book/fiction[@type='b']/author/@type" --value "Local" book.xml

We could use a xsl-document doThis.xsl and process the source.xml with xsltproc into a newFile.xml.

The xsl is based on the answer to this question.

Put this into a doThis.xsl file

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="UTF-8" omit-xml-declaration="no"/> 

<!-- Copy the entire document    -->

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<!-- Copy a specific element     -->

<xsl:template match="/book/fiction[@type='b']/author">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>

<!--    Do something with selected element  -->
            <xsl:attribute name="type">Local</xsl:attribute>

        </xsl:copy>
</xsl:template>

</xsl:stylesheet> 

Now we produce the newFile.xml

$:   xsltproc -o ./newFile.xml ./doThis.xsl ./source.xml 

This will be the newFile.xml

<?xml version="1.0" encoding="UTF-8"?>
<book>
   <fiction type="a">
      <author type=""/>
   </fiction>
   <fiction type="b">
      <author type="Local"/>
   </fiction>
   <Romance>
       <author type=""/>
   </Romance>
</book>

The expression used to find type b fiction is XPath.