本文介绍了使用sed在xml文件中查找和替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要查找并替换特定 xml 元素的值.条件如下:
I need to find and replace the value of the specific xml element. The conditions are as follows:
- 元素enabled的值必须从0改为1;
- enabled 必须是 somenode 元素的子元素
- the value of element enabled must be changed from 0 to 1;
- enabled must be the child of an somenode element
我的测试 xml 如下所示:
My test xml looks like this:
<somenode name="node1">
<some></some>
<enabled>0</enabled>
<some></some>
</somenode>
<someothernode name="node2">
<some></some>
<enabled>0</enabled>
<some></some>
</someothernode>
<somenode name="node3">
<some></some>
<enabled>0</enabled>
<some></some>
</somenode>
我希望第一个和第三个 enabled 元素会改变.到目前为止,我已经设法编写了这个 sed 命令:
I expect that first and third enabled elements would be changed. So far I have managed to write this sed command:
sed -n "1h;1!H;${;g;s|\(<somenode [^>]*>\)\(.*\)\(<enabled>\s*\)0\(\s*</enabled>\)\(.*</somenode>\)|\1\2\3 1 \4\5|g;p;}" test.xml
但它只改变了最后一个,我相信这是由于贪婪匹配.任何帮助将不胜感激.
but it changes only the last one, and I believe it is due to greedy match.Any help would be appreciated.
推荐答案
尽可能使用 xmlstarlet:
Use xmlstarlet if possible:
echo '
<root>
<somenode name="node1">
<some></some>
<enabled>0</enabled>
<some></some>
</somenode>
<someothernode name="node2">
<some></some>
<enabled>0</enabled>
<some></some>
</someothernode>
<somenode name="node3">
<some></some>
<enabled>0</enabled>
<some></some>
</somenode>
</root>
' > testfile.xml
xml val testfile.xml
xml el -v testfile.xml
xml ed --help
# version 1
xml ed -u "//somenode[1]/enabled" -v '1' \
-u "//somenode[2]/enabled" -v '1' \
testfile.xml
# version 2 (-L for in-place editing; xmlstarlet v1.0.2)
xml ed -L -u "//somenode[@name='node1']/enabled" -v '1' \
-u "//somenode[@name='node3']/enabled" -v '1' \
testfile.xml
这篇关于使用sed在xml文件中查找和替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!