Parsing semver with awk

From man awk:

Awk scans each input file for lines that match any of a set of patterns …

Parsing semver

Given version:

$ version=1.2.3

Major version

To get the major version:

$ echo $version | awk -F '.' '{print $1}'

Here, the input field separator is the period and we’re returning the 1st field.

A more concise way to write this is:

$ awk -F. '{print $1}' <<< $version

Minor version

To get the minor version:

$ awk -F. '{print $2}' <<< $version

Patch version

And to get the patch version:

$ awk -F. '{print $3}' <<< $version

Pre-release version

What about the pre-release version?

$ version=1.2.3-alpha.4

Instead of using the period as the field separator, we can use the hyphen:

$ awk -F- '{print $NF}' <<< $version

Here, $NF refers to the total number of fields (which is 2 in this case).

Please support this site and join our Discord!