微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在shell脚本中使用sed命令在XML文件中添加XML元素

我使用sed命令将xml元素插入到现有的xml文件中.

我有xml文件

<Students>
    <student>
        <name>john</>
        <id>123</id>
    </student>
    <student>
        <name>mike</name>
        <id>234</id>
    </student>
</Students>

我想添加新元素作为

<student>
        <name>NewName</name>
        <id>NewID</id>
    </student>

所以我的新xml文件将是

<Students>
    <student>
        <name>john</>
        <id>123</id>
    </student>
    <student>
        <name>mike</name>
        <id>234</id>
    </student>
    <student>
        <name>NewName</name>
        <id>NewID</id>
    </student>
</Students>

为此,我编写了shell脚本

#! /bin/bash

CONTENT="<student>
            <name>NewName</name>
            <id>NewID</id>
        </student>"

#sed -i.bak '/<\/Students>/ i \ "$CONTENT" /root/1.xml
sed -i.bak '/<\/Students>/ i \'$CONTENT'/' /root/1.xml

我收到错误

sed: can't read <name>NewName</name>: No such file or directory
sed: can't read <id>NewID</id>: No such file or directory
sed: can't read </student>: No such file or directory

并且在xml文件中,只有< student>被添加.
其余元素未添加.
有谁知道为什么这个错误

改变这个:
CONTENT="<student>
            <name>NewName</name>
            <id>NewID</id>
        </student>"

对此:

CONTENT="<student>\n<name>NewName</name>\n<id>NewID</id>\n</student>"

接着 :

C=$(echo $CONTENT | sed 's/\//\\\//g')
sed "/<\/Students>/ s/.*/${C}\n&/" file

原文地址:https://www.jb51.cc/bash/386895.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐