【问题标题】:shell script for the changing the element of xml [duplicate]用于更改 xml 元素的 shell 脚本 [重复]
【发布时间】:2013-08-13 14:47:18
【问题描述】:

我想将我的 xml“abc.xml”元素的值更改为存储在变量 $value 中的值,即

$value = 'abc';

<annotation>
    <filename>img_000001016592.png</filename>
    <folder>Rec_20121219_171905</folder>
    <source>
        <sourceImage>The MIT-CSAIL database of objects and scenes</sourceImage>
        <sourceAnnotation>LabelMe Webtool</sourceAnnotation>
    </source>
    <imagesize>
        <nrows>481</nrows>
        <ncols>640</ncols>
    </imagesize>
</annotation>

需要shell脚本,它有一个变量,它包含变量中的值,然后将abc.xml的元素文件名的值更改为变量中的值。

【问题讨论】:

    标签: xml bash shell


    【解决方案1】:

    也许你的意思是使用 sed。

    value='abc'
    sed -i "s|abc.txt|$value|g" abc.xml
    

    您必须在 shell 中运行它,或者作为带有标头 #!/bin/sh 的 shell 脚本运行。

    ---- 更新----

    #!/bin/sh
    value="something"
    sed -i "s|\(<filename>\)[^<>]*\(</filename>\)|\1${value}\2|" abc.xml
    

    如果需要在一行中替换多个实例,请在 sed 命令中添加g

    sed -i "s|\(<filename>\)[^<>]*\(</filename>\)|\1${value}\2|g" abc.xml
    

    【讨论】:

    • 我想将 abc.xml 元素的值(即“文件名”)更改为值“abc”。我认为我的问题没有很好地说明抱歉
    • 如果我使用 #!/bin/sh value='abc' sed -i "s|filename|$value|g" testxml.xml 然后文件名更改为 abc 而不是文件名的值即img_000001016592.png。我想把 img_000001016592.png 改成 abc
    • @Zeeshan 我做了更新,请检查。不过,这只适用于单行。如果 之间存在多行值,我建议您使用 XML 模块代替其他语言,如 Perl 或 Ruby。
    • 感谢您的解决方案 :) 它有效
    猜你喜欢
    • 2012-11-25
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多