在文件中查找String,替换linux下的一部分

Find String in file, replace a part of it under linux

我在名称为 /etc/rmm/config.xml:

的文件中有这样一个字符串
<Service Name="ssh" DisplayName="SSH Daemon" IsDaemon="true" DaemonType="SYSVINIT" Path="" StartParameters="" CanBeStopped="true" Enabled="true"/>

我想将 Enabled="true" 更改为 Enabled="false"。最好的方法是什么?

最简单、最直接的方法是使用 xmlstarlet一般来说,使用awksed这样的文本处理来处理XML个文件是不安全的,所以xmlstarlet(或full-fledged XSLT-1.0 处理器,如 xsltproc) 是正确的选择。

就这么简单:

xmlstarlet ed -u /Service/@Enabled -v "false" input.xml

输入文件如

<?xml version='1.0' encoding='utf-8'?>
<Service Name="ssh" DisplayName="SSH Daemon" IsDaemon="true" DaemonType="SYSVINIT" Path="" StartParameters="" CanBeStopped="true" Enabled="true"/>

输出是

<?xml version="1.0" encoding="utf-8"?>
<Service Name="ssh" DisplayName="SSH Daemon" IsDaemon="true" DaemonType="SYSVINIT" Path="" StartParameters="" CanBeStopped="true" Enabled="false"/>

根据需要调整-u后的XPath。例如,要将所有 Service 元素的 Enabled 属性从“true”更改为“false”,您可以使用

xmlstarlet ed -u //Service/@Enabled -v "false" input.xml