1

I have the following attribute:

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

How can I replace everything inside <client-version></client-version> to only change the value (1.2.8)?

So it would be:

<client-version>1.2.9</client-version>
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.

|improve this answer|||||
  • 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. – Cathal Mac Donnacha 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. – Cathal Mac Donnacha 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! – Cathal Mac Donnacha 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 
|improve this answer|||||
  • 2
    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. – Cathal Mac Donnacha 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.