Wednesday 7 February 2018

Python one-liner: return latest version

Today I need to find the latest version of some software. A normal ASCII sort (or even a numeric one), would be unreliable given the use of semantic version numbers. Instead I came up with this simple Python command that uses distutils LooseVersion to sort in the correct order:

python -c "import sys;from distutils.version import LooseVersion;print(sorted(sys.stdin.read().split(),key=LooseVersion)[-1])"

Simply pipe the input into stdin and Python will emit the latest version from the list of words or lines. For example:
$ echo octocat-0.0.2 octocat-10.0.3 octocat-1.2.0a octocat-6.1.0alpha | python -c "import sys;from distutils.version import LooseVersion;print(sorted(sys.stdin.read().split(),key=LooseVersion)[-1])"
returns
octocat-10.0.3