How to sort version numbers?

I would like to know how to sort version numbers, using bash or perl. I would like to sort file names that are program names with version numbers and extensions, such as hello-0.2.3.tar.gz and hello-0.10.3.tar.gz.

Version numbers of computer programs do not comply with the mathematical rule concerning the below-decimal-point part. Mathematics treats the part below decimal point differently from the integral part. In mathematics, the following sort order holds.

0.1 = 0.10 = 0.100 < 0.11 < 0.2 < 0.3

On the other hand, the version numbering system treats the part below decimal point in the same manner as the integral part. In the version numbering system, the following sort order holds.

0.1.0 < 0.2.0 < 0.3.0 < 0.10.0 < 0.11.0 < 0.100.0

The "sort" command on bash fails to achieve this latter result. How can one achieve this latter result?

Many thanks in advance.

Hi, try:

sort -bt. -k1,1 -k2,2n -k3,3n -k4,4n -k5,5n
1 Like

$$ sort -t"." -k 1,1 -k 2,2 -k 3,3 filename

here filename contains hello-0.2.3.tar.gz and all such patterns, one pattern per line.

Hi.

Recent versions of GNU ls have an ability like this. Using your list of version strings as a-v.tar.gz

#!/usr/bin/env bash

# @(#) s1	Demonstrate sort by version, GNU ls.

# Utility functions: print-as-echo, print-line-with-visual-space, debug.
# export PATH="/usr/local/bin:/usr/bin:/bin"
pe() { for _i;do printf "%s" "$_i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
edges() { local _f _n _l;: ${1?"edges: need file"}; _f=$1;_l=$(wc -l $_f);
  head -${_n:=3} $_f ; pe "--- ( $_l: lines total )" ; tail -$_n $_f ; }
db() { ( printf " db, ";for _i;do printf "%s" "$_i";done;printf "\n" ) >&2 ; }
db() { : ; }
C=$HOME/bin/context && [ -f $C ] && $C ls align

pl " Results:"
( pe "Plain	Version"
paste <( ls -1 a* ) <( ls -1v a* )
) |
align

exit 0

producing:

% ./s1

Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: Linux, 2.6.26-2-amd64, x86_64
Distribution        : Debian GNU/Linux 5.0.8 (lenny) 
bash GNU bash 3.2.39
ls (GNU coreutils) 6.10
align 1.7.0

-----
 Results:
Plain			Version
a-0.1.0.tar.gz		a-0.1.0.tar.gz
a-0.1.tar.gz		a-0.1.tar.gz
a-0.10.0.tar.gz		a-0.2.0.tar.gz
a-0.10.3.tar.gz		a-0.2.3.tar.gz
a-0.10.tar.gz		a-0.2.tar.gz
a-0.100.0.tar.gz	a-0.3.0.tar.gz
a-0.100.tar.gz		a-0.3.tar.gz
a-0.11.0.tar.gz		a-0.10.0.tar.gz
a-0.11.tar.gz		a-0.10.3.tar.gz
a-0.2.0.tar.gz		a-0.10.tar.gz
a-0.2.3.tar.gz		a-0.11.0.tar.gz
a-0.2.tar.gz		a-0.11.tar.gz
a-0.3.0.tar.gz		a-0.100.0.tar.gz
a-0.3.tar.gz		a-0.100.tar.gz

It appears best to have a consistent number of sub-versions in the version strings.

Best wishes ... cheers, drl