Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract version number from file in shell script

I'm trying to write a bash script that increments the version number which is given in

{major}.{minor}.{revision} 

For example.

1.2.13 

Is there a good way to easily extract those 3 numbers using something like sed or awk such that I could increment the {revision} number and output the full version number string.

like image 305
Dougnukem Avatar asked Jun 05 '11 19:06

Dougnukem


People also ask

What is $() in shell script?

$() – the command substitution. ${} – the parameter substitution/variable expansion.

What is $1 and $2 in shell script?

$0 is the name of the script itself (script.sh) $1 is the first argument (filename1) $2 is the second argument (dir1) $9 is the ninth argument.

How do I determine bash script version?

To find my bash version, run any one of the following command: Get the version of bash I am running, type: echo "${BASH_VERSION}" Check my bash version on Linux by running: bash --version. To display bash shell version press Ctrl + x Ctrl + v.


2 Answers

$ v=1.2.13 $ echo "${v%.*}.$((${v##*.}+1))" 1.2.14 

$ v=11.1.2.3.0 $ echo "${v%.*}.$((${v##*.}+1))" 11.1.2.3.1 

Here is how it works:

The string is split in two parts.

  • the first one contains everything but the last dot and next characters: ${v%.*}
  • the second one contains everything but all characters up to the last dot: ${v##*.}

The first part is printed as is, followed by a plain dot and the last part incremented using shell arithmetic expansion: $((x+1))

like image 158
jlliagre Avatar answered Sep 20 '22 16:09

jlliagre


Pure Bash using an array:

version='1.2.33' a=( ${version//./ } )                   # replace points, split into array ((a[2]++))                              # increment revision (or other part) version="${a[0]}.${a[1]}.${a[2]}"       # compose new version 
like image 45
Fritz G. Mehner Avatar answered Sep 18 '22 16:09

Fritz G. Mehner