【问题标题】:Add a new tag with value to an xml file node when its value matches an entry in the text file using shell script当其值与使用 shell 脚本的文本文件中的条目匹配时,将具有值的新标签添加到 xml 文件节点
【发布时间】:2017-07-31 10:05:21
【问题描述】:

我是 shell 脚本的新手。如果节点值在 txt 文件中,目标是添加一个新的兄弟节点。

这里是xml文件:animals.xml

<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>

这是文本文件:feed.txt

123
789

要添加的标签是

<eee>feed<eee>

鉴于以上示例,animals.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>

我尝试了以下但没有运气

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

sed 行不起作用。它仅在将 $f 替换为实际值时才起作用。但我不能那样做。

sed "/<bbb>123<\/bbb>/ s/.*/${feed_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

【问题讨论】:

  • 不要使用像sed这样的面向行的工具来处理XML。使用可识别 XML 的工具,例如 xmlstarlet。

标签: xml shell sed


【解决方案1】:

我建议使用xmlstarlet,像这样:

xmlstarlet ed -s '//bbb[text()='123' or text()='789']/..' \
    -t elem -n eee -u './/eee' -v feed animals.xml

如有必要,您可以使用sed 从feed.txt 生成xpath 表达式。

【讨论】:

    【解决方案2】:
    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
    

    【讨论】:

      猜你喜欢
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-03
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多