在Shell脚本中使用sed命令在XML文件中添加XML元素 [英] Adding XML element in XML file using sed command in shell script
本文介绍了在Shell脚本中使用sed命令在XML文件中添加XML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用sed命令将xml元素插入到现有的xml文件中.
I am using sed command to insert an xml element into the existing xml file.
我的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文件将是
So my new xml file will be
<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脚本编写为
For this I have written shell script as
#! /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>
.
其余元素未添加.
有人知道为什么会出现这个错误吗?
And in the xml file, only <student>
is added.
The remaining elements are not added.
Does anyone know why this error?
推荐答案
更改此内容:
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
这篇关于在Shell脚本中使用sed命令在XML文件中添加XML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文