Tip: Sort by Version Number
We want to sort a list of software products by version numbers. We want the highest version number of each product on the top of the list. Our example is a file
versions.txt
that looks as below:
ITNM 7.1.0.3 ITNM 7.2.0.11 ITNM 7.2.0.0 ITNM 7.1.1.5 ITNM 6.1.0.0 Tivoli 4.4.1.1 Tivoli 4.4.1.2 Tivoli 4.4.1.11 Tivoli 4.2.1.1 Tivoli Manager 1.1.1.1 Tivoli Manager 1.1.1.2 Tivoli Manager 1.1.1.11 Tivoli Manager 1.21.1.1 Tivoli Manager 1.3.1.1 Network Manager 4.4.1.1 Network Manager 4.4.1.2 Network Manager 4.4.1.11 Network Manager 4.2.1.1
If you run a recent version of the GNU coreutils you can use the -V
switch of sort to achieve this:
$ sort -r -V versions.txt ITNM 7.1.0.3 ITNM 7.2.0.11 ITNM 7.2.0.0 ITNM 7.1.1.5 ITNM 6.1.0.0 Tivoli 4.4.1.1 Tivoli 4.4.1.2 Tivoli 4.4.1.11 Tivoli 4.2.1.1 Tivoli Manager 1.1.1.1 Tivoli Manager 1.1.1.2 Tivoli Manager 1.1.1.11 Tivoli Manager 1.21.1.1 Tivoli Manager 1.3.1.1 Network Manager 4.4.1.1 Network Manager 4.4.1.2 Network Manager 4.4.1.11 Network Manager 4.2.1.1
In the above example the -r
switch affects all fields. As a result the package names are sorted in reverse order. Furthermore the
-V
switch is specific to recent versions of GNU sort. Older GNU versions as well as proprietary versions
of sort
don't understand the -V
switch.
To find a more portable command to sort our file by version number we first need to modify it and insert a dot(.) in each line between the software name
and the version number. ¹ We need this modification to make use of the -t"."
switch:
$ sort -t"." -k1,1 -k2,2nr -k3,3nr -k4,4nr -5,5nr versions.txt ITNM.7.2.0.11 ITNM.7.2.0.0 ITNM.7.1.1.5 ITNM.7.1.0.3 ITNM.6.1.0.0 Network Manager.4.4.1.11 Network Manager.4.4.1.2 Network Manager.4.4.1.1 Network Manager.4.2.1.1 Tivoli.4.4.1.11 Tivoli.4.4.1.2 Tivoli.4.4.1.1 Tivoli.4.2.1.1 Tivoli Manager.1.21.1.1 Tivoli Manager.1.3.1.1 Tivoli Manager.1.1.1.11 Tivoli Manager.1.1.1.2 Tivoli Manager.1.1.1.1
This variant works with most versions of sort
² including all GNU variants and therefore is the most portable way to sort our file by
version number. Furthermore this variant doesn't reverse sort the product names since the -r
switch here only affects individual fields.