Naga Naga - 1 month ago 17
Bash Question

Add Value to an attribute in XML File using shell script

I Want to edit XML file thru bash shell script. I am stuck in finding a solution - Kindly share your suggestion if this can be resolved via bash shell script.

I want to add -Dcustom.properties=/fs0/share/custom.properties value to jvmParameters attribute In applicationServerInstance tag if it does not exists.

Input File:

<?xml version="1.0" encoding="UTF-8"?>
<properties>
<applicationServer>
<applicationServerInstance id="app" serviceName=" App Server" rmiPort="15001" jvmParameters="-Xmx3072m" maxThreads="1000" programParameters="" distributed="false"/>
</applicationServer>
<blah>
</blah>
<blah abc="123">
</blah>
</properties>


Ideal Input File(Above file should be be updated as below):

<?xml version="1.0" encoding="UTF-8"?>
<properties>
<applicationServer>
<applicationServerInstance id="app" serviceName=" App Server" rmiPort="15001" jvmParameters="-Xmx3072m -Dcustom.properties=/fs0/share/custom.properties" maxThreads="1000" programParameters="" distributed="false"/>
</applicationServer>
<blah>
</blah>
<blah abc="123">
</blah>
</properties>

Answer

To build on the answer proposed by @Kenazov:

#!/usr/bin/env bash

INPUT=input.xml;
OUTPUT=config.xml

xmllint --format $INPUT |\
sed '/<applicationServerInstance/{/-Dcustom.properties=\/fs0\/share\/custom.properties/!s/\(jvmParameters="[^"]*\)"/\1 -Dcustom.properties=\/fs0\/share\/custom.properties"/}' \
> $OUTPUT