Reputation: 367
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>
Upvotes: 0
Views: 972
Reputation: 15461
With sed:
sed -i '/<applicationServerInstance/{/-Dcustom\.properties=\/fs0\/share\/custom\.properties/!s/\(jvmParameters="[^"]*\)"/\1 -Dcustom.properties=\/fs0\/share\/custom.properties"/}' file
When <applicationServerInstance
is found, if -Dcustom.properties=/fs0/share/custom.properties
is not found in the line, it's appended as attribute value to jvmParameters
.
As @1sloc point out in comment, you'd better sanitize your file using for instance xmllint
before executing this sed to make sure that <applicationServerInstance
and jvmParameters
are on the same line.
The -i
flag is to edit the file in place.
Upvotes: 1
Reputation: 1180
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
Upvotes: 1