在特殊标签之间的数字前添加零

问题描述 投票:0回答:1

我知道将前导零添加到数字并不复杂。但是,我正在寻找一种最佳解决方案,将前导零仅添加到<SpecialTag>0</SpecialTag>之间的值以使其成为5位数字。

<?xml version="1.0" encoding="ISO-8859-1" standalone="yes" ?>
<Root>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>0</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>12</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>12345</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>1234</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
</Root>

预期结果应该如下:

<?xml version="1.0" encoding="ISO-8859-1" standalone="yes" ?>
<Root>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>00000</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>00012</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>12345</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>01234</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
</Root>
bash shell sed xmlstarlet
1个回答
1
投票

使用xsltproc建议的解决方案!):

具有XLST文件transform.xsl:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

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

    <xsl:template match="SpecialTag">
        <xsl:copy>
            <xsl:value-of select="format-number(node(), '00000')" />
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

运行:

$ xsltproc transform.xml input.xml

使用sed

sed --regexp-extended 's@<SpecialTag>([0-9]+)</SpecialTag>@<SpecialTag>0000000\1</SpecialTag>@;s@0*([0-9]{5,})@\1@'

使用perl

perl -pe 's@<SpecialTag>([0-9]+)</SpecialTag>@sprintf("<SpecialTag>%05d</SpecialTag>",$1)@e'

使用awk

awk '{gsub( /<SpecialTag>[0-9]+<\/SpecialTag>/, sprintf("<SpecialTag>%05d</SpecialTag>", gensub(/[^0-9]/, "","g"))); print}'
© www.soinside.com 2019 - 2024. All rights reserved.