1

I have the following node in an XML document:

<client-version>1.2.8</client-version>

How can I replace replace the node's value, 1.2.8, with 1.2.9?

Wanted output:

<client-version>1.2.9</client-version>
1
7

You would use an XML parser to do this. For example xmlstarlet (a command line XML tool):

$ xmlstarlet ed -u '//client-version' -v '1.2.9' file.xml
<?xml version="1.0"?>
<client-version>1.2.9</client-version>

The above command would locate all occurrences of the client-version document node and change their values to the string 1.2.9.

To only change the ones that are 1.2.8, you would use

xmlstarlet ed -u '//client-version[text() = "1.2.8"]' -v '1.2.9' file.xml

Redirect the output to a new file, inspect it and rename it to the original filename, or run xmlstarlet with its -L or --inplace options to edit the file in-place.


Using xq, from yq, from https://kislyuk.github.io/yq/, which allows you to use jq expressions to modify XML documents:

xq -x '(..|."client-version"? // empty) |= "1.2.9"' file.xml

This updates the value of each client-version node to 1.2.9 regardless of where in the document it is located.

The string 1.2.9 could be inserted from a variable like so:

new_version=1.2.9
xq -x --arg ver "$new_version" '(..|."client-version"? // empty) |= $ver' file.xml
4
  • I'm currently using bamboo to run this script as a task, bamboo is running CENTOS and when I use xmlstarlet it says the command is not found. Hence why I went down the sed route. Mar 15 '19 at 15:38
  • Running it as a shell script on bamboo. CentOS 6. Would xmlstartlet be available on this? Do I need to install it first? Apologies I'm a bit new to it. Mar 15 '19 at 15:48
  • 1
    @CathalMacDonnacha See, for example, here: How to instal/setup XMLStarlet in Linux?
    – Kusalananda
    Mar 15 '19 at 17:33
  • Thanks for that! Mar 19 '19 at 13:37
0

Tried with below awk command and it worked fine

awk '$0 ~ /^<client-version>/ && $0 ~ /<\/client-version>/{gsub("1.2.8","1.2.9",$0)}1' orginalfile  >temperorayfile && mv temperorayfile  orginalfile 
2
  • 3
    It might work fine once, but it's wrong, so don't use it in production code. It only takes tiny insignificant variations in the formatting of the XML to break it. When working with XML, always use XML-aware tools.
    – user32929
    Mar 15 '19 at 16:42
  • @user32929 I'm trying to run this as a shell script on bamboo. CentOS 6. Would xmlstartlet be available on this? Do I need to install it first? Apologies I'm a bit new to it. Mar 15 '19 at 16:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.