Ultimately, I wanted to set the latest version as an environment variable, so supplementing the selected answer (which provided me the correct sorting):
export LATEST_VERSION=$(printf '%s\n' * | sort -rV | head -1)
I have a directory with the following directory names:
ls -1r .
2.0
1.8
16.1
16.0
15.5
15.0
14.5
14.1
14.0
1.3
1.2
1.1.5
1.1.3
1.1.2
I would like to sort them to get the latest release version:
ls -1r . | head -1
16.1
So the underlying order should look like this:
16.1
16.0
15.5
15.0
14.5
14.1
14.0
2.0
1.8
1.3
1.2
1.1.5
1.1.3
1.1.2
Any help would be greatly appreciated. Simpler the better, but I'm open to any solution. Thanks!
Modern GNU sort offers a -V
flag for sorting according to version number rules:
$ printf '%s\n' * | sort -rV
16.1
16.0
15.5
15.0
14.5
14.1
14.0
2.0
1.8
1.3
1.2
1.1.5
1.1.3
1.1.2
Note that the above does not use ls
. As a general rule, you shouldn't parse the output of ls(1).
From man sort
:
-V, --version-sort
natural sort of (version) numbers within text
The above is from the GNU man page.
FreeBSD's sort also supports -V
.
Apple's sort is a GNU sort from the year 2005 which predates support for the -V
option. A work-around can be found here. (Hat tips: l'L'l, mklement0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With