Parsing semver with awk

This post goes over how to parse semantic versioning with awk:

From man awk:

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


Given version:


Major version

To get the major version:

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

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

To get the patch version:

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

Pre-release version

What about the pre-release version alpha.4?


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

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

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

Please support this site and join our Discord!