sed replace xml tag

独自空忆成欢 提交于 2020-12-26 23:26:48

问题


I want to replace value inside a tag in an xml file using sed.

<version> xxxx-SS </version>

I want to replace xxxx-SS with some shell variable $ver . The final result should be

<version>$ver</version>

The sed command should also quit after replacing the first instance.

So far I have been able to only append to the xxxx-SS and not been able to quit after the first match.

sed 's#\(<version>\)*\(</version>\)#\1'$ver'\2#g' test.xml

This only appends the value between -SNAPSHOT tag.Basically makes it xxxx-SS$ver


回答1:


You may try to use awk, it would more simple to achieve what you desire,

$ cp test.xml test_orig.xml

$ awk '/<version> xxxx-SS <\/version>/{gsub(/<version> xxxx-SS <\/version>/,"<version> $ver </version>",$0)}1' test_orig.xml > test.xml
$ cat test.xml
...
<version> $ver </version>
...

$ rm test_orig.xml

The command would substitute xxxx-SS to test (modify the var value to what you want)




回答2:


Using xml/html parsers is the right way to manipulate xml/html documents. Don't use sed/awk tools for such cases.

xmlstarlet solution:

xmlstarlet ed -u "//version[1]" -v $ver test.xml
  • ed - edit mode

  • -u - update action

  • //version[1] - xpath expression to select the first version tag

  • -v $ver - the new value for selected node



来源:https://stackoverflow.com/questions/44644590/sed-replace-xml-tag

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!