我使用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
改变这个:
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