Search code examples
bashxsltawksed

Need to replace integers with floating points in lines containing a specific string in an xml formatted file


For reasons related to app functionality, we need to massage certain data incoming to a system by replacing an integer value with a fixed length decimal value

Example:

Before

<smile:ordinary code:type="Fields" code:value="25">

After

<smile:ordinary code:type="Fields" code:value="25.000000000">`

I had tried to used a sed command in place to replace with a regex group such as the one below

sed -i 's/\(ordinary.*"[0-9]\+\)/\1.000000000/'

This works fine but there's a file watcher that triggers when the file is modified and if it receives a well formatted file, it ends up adding an extra set of 0s

<smile:ordinary code:type="Fields" code:value="25.000000000.000000000">

I've also struggled to get this working with awk and printf but ideally, i'd replace the integer strictly with a decimal. I've considered using an xsl filter transform as well but I'm not quite as well versed there as with shell commands. I'm open to all suggestions including possibly writing a shell script to loop through each line I guess.


Solution

  • Very easily done in XSLT. It just needs a stylesheet with two rules, the standard identity template that copies elements unchanged by default plus a rule

    <xsl:template match="smile:ordinary/@code:value">
      <xsl:attribute name="code:value">
        <xsl:value-of select="format-number(., '#.000000000')"/>
      </xsl:attribute>
    </xsl:template>
    

    Plus the required namespace declarations, of course.