bash regex to match semantic version number

lukemh picture lukemh · Jun 20, 2014 · Viewed 16k times · Source

I have the following:

versionNumber=$(sw_vers -productVersion) # Finds version number

versionShort=${versionNumber:0:4}  # Cut string to 1 decimal place for calculation

which works when versions are like this:

10.9.2
10.9.5

but it will not match

10.10.3

as it will return only

10.1

but I want the versionShort to be set to

10.10

I am wanting to match the major version, the first dot and the minor version as above.

Answer

Amadan picture Amadan · Jun 20, 2014

Regexpless solution - cut off last dot and whatever follows it:

versionShort=${versionNumber%.*}