Friday, July 29, 2022

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

Issue

I have a string like this in a file with the name /etc/rmm/config.xml:

<Service Name="ssh" DisplayName="SSH Daemon" IsDaemon="true" DaemonType="SYSVINIT" Path="" StartParameters="" CanBeStopped="true" Enabled="true"/>

I want to change Enabled="true" to Enabled="false". What is the best way to do it?


Solution

The easiest and most direct way to achieve this is using xmlstarlet. In general, it is unsafe to use text processing like awk or sed to handle XML files, so xmlstarlet (or a full-fledged XSLT-1.0 processor like xsltproc) is the way to go.

It is easy like that:

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

With an input file like

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

the output is

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

Adjust the XPath after -u according to your needs. For example, to change all Service element's Enabled attributes from "true" to "false", you could use

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


Answered By - zx485
Answer Checked By - David Marino (WPSolving Volunteer)