1

我正在尝试仅使用 Linux CLI 工具处理 XML 文件。我要解决的主要问题是将特定 XML 标记的内容复制到新标记中,如下所示:

<date>Wednesday</date>
<name>The Name</name>
<anotherattribute>Attribute</anotherattribute>

进入:

<date>Wednesday</date>
<id>The Name</id>
<name>The Name</name>
<anotherattribute>Attribute</anotherattribute>

我一直在尝试使用 sed 来解决这个问题,并且已经能够识别标签,并将其复制到保持缓冲区中:

/<name>/{
h
i\
<id>
G
a\
</id>
}

但这会导致:

<date>Wednesday</date>
<id>
<name>The Name</name>
<name>The Name</name>
</id>
<anotherattribute>Attribute</anotherattribute>

任何帮助深表感谢。

4

1 回答 1

1

试试这个:

sed '/<name>/{h;s/name>/id>/g;G}'

您也可以尝试xmlstarlet

cat input.xml |
    xmlstarlet ed -i //name -t elem -n id -v '' |
        xmlstarlet ed -u //id -x '../name'
于 2012-08-31T01:33:07.343 回答