在 Bash 中搜索和替换 XML 格式的文本块
Searching and replacing a block of XML formatted text in Bash
我一直想弄清楚如何搜索一段 XML 格式的文本并在 Bash 中修改它。我要处理的文件是一个格式为XML的模拟文件。假设文件包含多个 XML 语句块:
<mote>
<breakpoints />
<interface_config>
org.contikios.cooja.interfaces.Position
<x>0.0</x>
<y>75.0</y>
<z>0.0</z>
</interface_config>
<interface_config>
org.contikios.cooja.mspmote.interfaces.MspClock
<deviation>1.0</deviation>
</interface_config>
<interface_config>
org.contikios.cooja.mspmote.interfaces.MspMoteID
<id>4</id>
</interface_config>
<motetype_identifier>sky2</motetype_identifier>
</mote>
我要搜索的是这里的XML个语句块:
<id>4</id>
</interface_config>
<motetype_identifier>sky2</motetype_identifier>
并替换为
<id>4</id>
</interface_config>
<motetype_identifier>sky3</motetype_identifier>
这些语句前后的其余 XML 语句将保持不变。这将使我能够在 Bash.
中的脚本中将 mote 类型节点 4 从 sky2 更改为 sky3
xmlstarlet ed --omit-decl -u "//mote[interface_config/id='4']/motetype_identifier" -v 'sky3' file.xml
输出:
<mote>
<breakpoints/>
<interface_config>
org.contikios.cooja.interfaces.Position
<x>0.0</x>
<y>75.0</y>
<z>0.0</z>
</interface_config>
<interface_config>
org.contikios.cooja.mspmote.interfaces.MspClock
<deviation>1.0</deviation>
</interface_config>
<interface_config>
org.contikios.cooja.mspmote.interfaces.MspMoteID
<id>4</id>
</interface_config>
<motetype_identifier>sky3</motetype_identifier>
</mote>
如果您想就地编辑 file.xml,请添加选项 -L。
参见:xmlstarlet ed --help
我一直想弄清楚如何搜索一段 XML 格式的文本并在 Bash 中修改它。我要处理的文件是一个格式为XML的模拟文件。假设文件包含多个 XML 语句块:
<mote>
<breakpoints />
<interface_config>
org.contikios.cooja.interfaces.Position
<x>0.0</x>
<y>75.0</y>
<z>0.0</z>
</interface_config>
<interface_config>
org.contikios.cooja.mspmote.interfaces.MspClock
<deviation>1.0</deviation>
</interface_config>
<interface_config>
org.contikios.cooja.mspmote.interfaces.MspMoteID
<id>4</id>
</interface_config>
<motetype_identifier>sky2</motetype_identifier>
</mote>
我要搜索的是这里的XML个语句块:
<id>4</id>
</interface_config>
<motetype_identifier>sky2</motetype_identifier>
并替换为
<id>4</id>
</interface_config>
<motetype_identifier>sky3</motetype_identifier>
这些语句前后的其余 XML 语句将保持不变。这将使我能够在 Bash.
中的脚本中将 mote 类型节点 4 从 sky2 更改为 sky3xmlstarlet ed --omit-decl -u "//mote[interface_config/id='4']/motetype_identifier" -v 'sky3' file.xml
输出:
<mote>
<breakpoints/>
<interface_config>
org.contikios.cooja.interfaces.Position
<x>0.0</x>
<y>75.0</y>
<z>0.0</z>
</interface_config>
<interface_config>
org.contikios.cooja.mspmote.interfaces.MspClock
<deviation>1.0</deviation>
</interface_config>
<interface_config>
org.contikios.cooja.mspmote.interfaces.MspMoteID
<id>4</id>
</interface_config>
<motetype_identifier>sky3</motetype_identifier>
</mote>
如果您想就地编辑 file.xml,请添加选项 -L。
参见:xmlstarlet ed --help