0

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>

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

To make sure, the file should first be sanitized using xmllint or the likes. Only after such a sanitation, we can be sure that applicationServerInstance and jvmParameters are on the same line, for instance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.