0

I need a bash script for updating part of XML element value according to some other dynamic property.

For example, the XML file:

<?xml version="1.0"  encoding="ISO-8859-1"?>
 <Configure class="org.eclipse.something">
   <Set name="foo">foo-val</Set>
   <Set name="bar">bar-val</Set>
   <Set name="my-elm">/dont/matter/THIS_ONE_NEED_TO_BE_UPDATED</Set>
 </Configure>

Tried to use xmlstarlet with regexing, but it's not providing the result I want. I'm working on OSX 10.12.

6
  • 2
    Have you tried something yourself? Commented Jan 2, 2017 at 13:29
  • 1
    Have you checked a XML parser? Commented Jan 2, 2017 at 13:31
  • If the value to change is only present once in your file, a simple sed -i 's/oldvalue/newvalue/' file.xml is enough Commented Jan 2, 2017 at 13:33
  • xmlstartlet for instance? Commented Jan 2, 2017 at 13:33
  • Yes, I tried regexing the text and xmlstarlet, didn't succeed to replace just part of the value. Commented Jan 2, 2017 at 13:33

1 Answer 1

2

Using xmlstarlet with below xpath expression worked fine for me. The below expression does in-pace substitution (-L flag) of the XML file

xmlstarlet edit -L -u "/Configure/Set[@name='my-elm']" -v '/dont/matter/THIS_ONE_NEED_TO_BE_UPDATED' xml-file

Drop the -L flag to check if the replacement is occurring properly, and once successful add the same.

Checked on xmlstarlet (1.6.1) on OS X

Though it is strictly NOT advised to use sed for xml updates, this below logic will work for you,

sed "s/\(<Set name=\"my-elm\".*>\)[^<>]*\(<\/Set.*\)/\1\/dont\/matter\/THIS_ONE_NEED_TO_BE_UPDATED\2/" xml-file

add the -i.bak for in-place substitution of the file.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. It works :) Two questions please. 1) Is there a way to do it without xmlstarlet? There are machines that don't have it installed 2) Is there a nice regex trick to update just the THIS_ONE_NEED_TO_BE_UPDATED part?
@StasS: Refer my update which should solve your problem,

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.