我有一个名为abc.xml的文件
<Engine name="private" defaultHost="localhost">
<Model name="qwerty"/>
<Host name="localhost" />
</Engine>
我想在Host标签中添加子标签,以便我修改的abc.xml如下所示。
<Engine name="private" defaultHost="localhost">
<Model name="qwerty"/>
<Host name="localhost" company="jaguar" >
<Partner name="xxx" />
<Partner name="yyy" />
</Host>
</Engine>
如何使用SED或awk命令实现上述更改?
答案 0 :(得分:1)
使用xmlstarlet
,你可以这样做:
xmlstarlet ed -i //Host -t attr -n company -v jaguar \
-s //Host -t elem -n Partner \
-i //Host/Partner -t attr -n name -v xxx \
-s //Host -t elem -n Partner \
-i //Host/Partner[2] -t attr -n name -v yyy abc.xml
现在,这看起来更复杂,但它知道你文件的结构。
答案 1 :(得分:0)
cat ins.txt
<Host name="localhost" company="jaguar" >
<Partner name="xxx" />
<Partner name="yyy" />
cat abc.xml
<Engine name="private" defaultHost="localhost">
<Model name="qwerty"/>
<Host name="localhost" />
</Engine>
cat script.awk
BEGIN{RS=""}
ARGV[1]==FILENAME{ins=$0;RS="\n";next}
/<Host/ {print ins;next} 1
awk -f script.awk ins.txt abc.xml
<Engine name="private" defaultHost="localhost">
<Model name="qwerty"/>
<Host name="localhost" company="jaguar" >
<Partner name="xxx" />
<Partner name="yyy" />
</Engine>