当xml文件节点的值与使用shell脚本的文本文件中的条目匹配时,向xml文件节点添加一个具有值的新标记
我不熟悉shell脚本。如果节点值在txt文件中,则目标是添加新的同级节点 这是xml文件:anives.xml当xml文件节点的值与使用shell脚本的文本文件中的条目匹配时,向xml文件节点添加一个具有值的新标记,xml,shell,sed,Xml,Shell,Sed,我不熟悉shell脚本。如果节点值在txt文件中,则目标是添加新的同级节点 这是xml文件:anives.xml <aaa> <bbb>123</bbb> <ccc>cat</ccc> <ddd>dog</ddd> </aaa> <aaa> <bbb>456</bbb> <ccc>fox</ccc>
<aaa>
<bbb>123</bbb>
<ccc>cat</ccc>
<ddd>dog</ddd>
</aaa>
<aaa>
<bbb>456</bbb>
<ccc>fox</ccc>
<ddd>bat</ddd>
</aaa>
<aaa>
<bbb>789</bbb>
<ccc>rat</ccc>
<ddd>pig</ddd>
</aaa>
要添加的标记是
<eee>feed<eee>
feed
鉴于上述示例,应将anives.xml内容更新为
<aaa>
<bbb>123</bbb>
<ccc>cat</ccc>
<ddd>dog</ddd>
<eee>feed</eee>
</aaa>
<aaa>
<bbb>456</bbb>
<ccc>fox</ccc>
<ddd>bat</ddd>
</aaa>
<aaa>
<bbb>789</bbb>
<ccc>rat</ccc>
<ddd>pig</ddd>
<eee>feed</eee>
</aaa>
123
猫
狗
喂养
456
狐狸
蝙蝠
789
老鼠
猪
喂养
我尝试了以下方法,但没有成功
feed_content="<eee>feed</eee>"
feed_tag=$(echo $feed_content | sed 's/\//\\\//g')
while IFS= read -r f
do
#Check if there is a <bbb> tag with value equals to f. If there is,append the <eee>feed</eee>
sed "/<bbb>$f<\/bbb>/ s/.*/${feed_tag}\n&/" $f
done < feed.txt
feed\u content=“feed”
feed\u标记=$(echo$feed\u内容| sed's/\/\\//\\\//g')
而IFS=read-rf
做
#检查是否有值等于f的标记。如果有,请附加提要
sed“/$f/s/*/${feed_tag}\n&/“$f
完成
sed行不起作用。它只在用实际值替换$f时起作用。但我不能那样做
sed "/<bbb>123<\/bbb>/ s/.*/${feed_tag}\n&/" $f
sed”/123/s/*/${feed\u tag}\n&/“$f
已解决:
事实证明,$f包含很多尾随空格。我只需要调整一下,sed声明就行了
animals_xml=animals.xml
feed_content="<eee>feed</eee>"
feed_tag=$(echo $feed_content | sed 's/\//\\\//g')
while IFS= read -r f
do
#Check if there is a <bbb> tag with value equals to f. If there is,append the <eee>feed</eee>
f="${f#"${f%%[![:space:]]*}"}"
f="${f%"${f##*[![:space:]]}"}"
sed "/<bbb>$f/ s/.*/&\n\t${feed_tag}/" $animals_xml
done < feed.txt
animates\u xml=animates.xml
feed_content=“feed”
feed\u标记=$(echo$feed\u内容| sed's/\/\\//\\\//g')
而IFS=read-rf
做
#检查是否有值等于f的标记。如果有,请附加提要
f=“${f#”${f%%[![:空格:]*}”
f=“${f%”${f##*[![:空格:]}”
sed“/$f/s/*/&\n\t${feed\u tag}/“$animals\u xml
完成
我建议使用xmlstarlet
,如下所示:
xmlstarlet ed -s '//bbb[text()='123' or text()='789']/..' \
-t elem -n eee -u './/eee' -v feed animals.xml
如有必要,您可以使用
sed
从feed.txt
生成xpath表达式,我建议使用xmlstarlet
,如下所示:
xmlstarlet ed -s '//bbb[text()='123' or text()='789']/..' \
-t elem -n eee -u './/eee' -v feed animals.xml
str="<eee>feed</eee>"
while read id; do
sed -ri '/<aaa>/{:a;N;/<\/aaa>/!ba;/<bbb>'"$id"'/s#(.*\n)(\s+)([^\n]+\n)#&\2'"$str"'\n#}' animals.xml
done < feed.txt
如有必要,您可以使用sed
从feed.txt
生成xpath表达式
str="<eee>feed</eee>"
while read id; do
sed -ri '/<aaa>/{:a;N;/<\/aaa>/!ba;/<bbb>'"$id"'/s#(.*\n)(\s+)([^\n]+\n)#&\2'"$str"'\n#}' animals.xml
done < feed.txt
读取id时;做
sed-ri'/{:a;N;//!ba;/'“$id”/s#(.*\N)(\s+)([^\N]+\N)#和\2'$str'\N#}animals.xml
完成str=“feed”
读取id时;做
sed-ri'/{:a;N;//!ba;/'“$id”/s#(.*\N)(\s+)([^\N]+\N)#和\2'$str'\N#}animals.xml
完成
不要使用面向行的工具,如sed
来处理XML。使用支持XML的工具,如xmlstarlet
。不要使用面向行的工具,如sed
来处理XML。使用支持XML的工具,如xmlstarlet
。