How would I increment the (version) value of an XML element using AWK?

732 views Asked by At

I have an XML file that contains a version number (major.minor.build) element and I'd like to increment that value using awk (leaving the rest of the file untouched).

For example, when the file contains:

<ProductVersion>1.0.1</ProductVersion>

I'd like it to be changed to:

<ProductVersion>1.0.2</ProductVersion>

If it simplifies things, we can assume that the ProductVersion element will always be on a line on it's own.

[NB. I know this is a quick and dirty way of manipulating XML, but it meets my current needs - i.e. creating a script, for my personal use, to be run using Mono's xbuild on the Mac. I'm using the Exec task instead of attempting to get the MSBuild Community Tasks, etc. working on the Mac (for now).]

2

There are 2 answers

0
kurumi On BEST ANSWER

Since we can assume the product version is on a line by its own, here's one way

awk -F"[><]" '/<ProductVersion>/{ 
    n=split($3,a,".")
    a[n]=a[n]+1
    s=a[1];for(i=2;i<n;i++)s=s"."a[i]; 
    $3=s"."a[n]
    $0="<ProductVersion>"$3"</ProductVersion>"}1' file

Note it only increments the last number.

0
Dennis Williamson On

Use XSH2:

#!/usr/local/bin/xsh
open prodver.xml;
$v = //ProductVersion;
perl {@a = split(/\./, $v);};
$m = {$a[2]};
$m += 1;
map :i { s/\.\d+$/.$m/ } //ProductVersion;
save;