1

How do I get the version number from a file and increase the version with 1? I would like to store the version to a variable, increase it with one en save the new version in the file.

Let's say I have a simple config file (application.config) like this:

[section1]
Some = variables

[Version]
version = 1.0

The version always starts with "version = " (without the quotes, I added them to demonstrate the space after =). I would like to:

  • Change 1.0 to 1.1 (1.9 should get 1.10, 1.99 should get 1.100 etc).
  • Store 1.1 to a variable to use it in another part of my script.

I tried it with sed:

sed -i -r 's/version = [0-9]+.[0-9]+/version = $Version/I' application.config

This works if I manually enter $version, hoe do I get it from the file itself?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Does this answer your question? [Difference between single and double quotes in Bash](https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash) – KamilCuk Mar 27 '20 at 14:20
  • Does this answer your question? [How to find/replace and increment a matched number with sed/awk?](https://stackoverflow.com/questions/14348432/how-to-find-replace-and-increment-a-matched-number-with-sed-awk) – Yohann Mar 27 '20 at 14:24
  • I came across that question in my search. But I can't get that example to work in my situation. If I use `sed -r 's/(.*)(\version =)([0-9]+)(.*)/echo "\1\2$((\3+1))\4"/ge' application.config` it stays 1.0. – user6753355 Mar 27 '20 at 14:31
  • Using `s/.../.../e` is a *really* bad idea -- same family of security issues as awk's shell-invocation support. – Charles Duffy Mar 27 '20 at 16:02

3 Answers3

2
version=$(sed -nE 's/version = ([0-9]+.[0-9]+)/\1/Ip' application.config)
lastnumber=$((${version##*.}+1))
newversion=${version%.*}.$lastnumber
sed -i -E "s/version = [0-9]+.[0-9]+/version = $newversion/I" application.config

Notice that I have changed -r to -E in your sed. They are equivalent but the latter is understood by other sed implementations.

Quasímodo
  • 3,812
  • 14
  • 25
1

This might help you:

grep "version = [0-9]*.[0-9]*" <filename> | awk -F '.' '{print $1 "." 1+$2}'
grep -E "version = [0-9]+.[0-9]+" <filename> | awk -F '.' '{print $1 "." 1+$2}'

First search for the word "version", then split the line in two pieces, based on the dot separator, and add "1" to the second part.

Remark : the -E is needed in order for the plus-signs to work.

Dominique
  • 16,450
  • 15
  • 56
  • 112
0

Just to show another way that you should avoid, because it is illegible and unmanageable. Since you know the prefix you can use grep's perl-regexp engine to extract the whole version, then replace the dot with a comma and bash will add the digit after the comma without extracting it in a further variable.

sed -E -i "s/\.[[:digit:]]+/\.$(($(grep -Po "(?<=version\s=\s)\d+\.\d+$" conf.ini | sed "s/\./,/g")+1))/g" conf.ini