nizzoball
nizzoball

Reputation: 21

Replacing a value in XML file via bash

I have an XML file that I am trying edit via xmlstarlet in a bash script but I am unable to find any examples that have an xml formatted the same way as this one. Below is the xml

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="StringCollections" type="ALINetCoreConsole.Config.StringCollections, ALINetCoreConsole"/>
  </configSections>
  <appSettings>
    <add key="TCPAddress" value="192.168.xx.xx"/>
    <add key="TCPPort" value="2101" />
    <add key="ParsingFilesDirectory" value="/app/aliparsing"/>
    <add key="MessageBossAddress" value="messageboss:9092"/>
    <add key="AliRulesetReloadMinutes" value="30"/>
    <add key="PsapId" value=""/>
    <add key="MessageStarter" value="2"/>
    <add key="MessageEnder" value="3"/>
    <!-- Possible values are: Warn, Info, Debug -->
    <add key="LogLevel" value="Warn"/>
  </appSettings>

  <StringCollections>
    <HeartbeatValues>
      <add message="K"/>
      <add message="H"/>
    </HeartbeatValues>
  </StringCollections>
</configuration>

The specific value I am trying to change via xmlstarlet is value="192.168.xx.xx"

So far I have figured out how to delete the entire line but something isn't clicking with me on the correct syntax to just change the IP address in the Value field.

I currently have the script written to use sed to find and replace the IP but it's ugly and relies on cut/rev so if for some reason that particular line had an extra space at the end or something similar then it would fail. I am looking for a more elegant and reliable solution with xmlstarlet.

Upvotes: 0

Views: 361

Answers (1)

Cyrus
Cyrus

Reputation: 88553

Update an attribute with xmlstartlet:

xmlstarlet edit --update '//add[@value="192.168.xx.xx"]/@value' --value '1.2.3.4' file.xml

or

xmlstarlet edit --update '//add[@key="TCPAddress"]/@value' --value '1.2.3.4' file.xml

Upvotes: 1

Related Questions