How to extract a version number using sed

regexsed

I'm trying to find the best regular expression to extract a version number from a string. For example:

 echo "Version 1.2.4.1 (release mode)" | sed -ne 's/.*\([0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+\).*/\1/p'

The problem here is that it works only if the version number is in the format "a.b.c.d". If someone decides to add or remove a digit ("a.b.c.d.e", "a.b.c"), it will break. So I'd like to factorize the regex and tell sed that I want:

(1 or more numbers followed by a dot) x 1 or more times, followed by a number.

I can't find how to "group" the "1 or more numbers followed by a dot" so I can tell I want that pattern at least once. I've tried this but it doesn't work:

\([0-9]\+\.\)\+

Any ideas ?

Best Answer

Try next 'sed' command:

$ echo "Version 1.2.4.1 (release mode)" | sed -ne 's/[^0-9]*\(\([0-9]\.\)\{0,4\}[0-9][^.]\).*/\1/p'
1.2.4.1

It uses the {i,j} syntax, which selects the expression a number of times between the first and the last number. There souldn't be any numbers in the string before the version number.

Another examples:

$ echo "Version 1.2.4.1.6 (release mode)" | sed -ne 's/[^0-9]*\(\([0-9]\.\)\{0,4\}[0-9][^.]\).*/\1/p'
1.2.4.1.6 
$ echo "Version 1.2 (release mode)" | sed -ne 's/[^0-9]*\(\([0-9]\.\)\{0,4\}[0-9][^.]\).*/\1/p'
1.2 
$ echo "Version 1.2. (release mode)" | sed -ne 's/[^0-9]*\(\([0-9]\.\)\{0,4\}[0-9][^.]\).*/\1/p'
$ 

EDIT to comments:

$ echo "Version 1.2.4.1.90 (release mode)" | sed -nre 's/^[^0-9]*(([0-9]+\.)*[0-9]+).*/\1/p'
Related Question