3

I want to extract a version number from some strings in bash without using too much additional packages. So far I tried sed.

Here is the API :

3.81-8.1ubuntu1.1    should give :  3.81
2.68-1ubuntu2        should give :  2.68
1:1.11.3-1ubuntu2    should give :  1.11.3

And here is my sed command so far:

echo ... | sed -r 's/.*([0-9\.]+).*/\1/'

However, the opening .* is too greedy, especially with the last case. I've tried some .*? and .\{-} without any success.

I can do it in two passes, but I would rather learn how to do it in one.

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
Offirmo
  • 18,962
  • 12
  • 76
  • 97
  • Possible duplicate of http://stackoverflow.com/questions/1103149/non-greedy-regex-matching-in-sed –  Jan 22 '13 at 17:21
  • @Tinctorius I'd rather not use perl, as stated in my question. But if there is no better way... – Offirmo Jan 22 '13 at 17:23

2 Answers2

8

is this ok for you?

 grep -Po "[\d\.]*(?=-)" file

example:

kent$  cat tt
3.81-8.1ubuntu1.1
2.68-1ubuntu2
1:1.11.3-1ubuntu2

kent$  grep -Po "[\d\.]*(?=-)" tt
3.81
2.68
1.11.3
Kent
  • 189,393
  • 32
  • 233
  • 301
1

To overcome the greediness you need to be more strict with the regexp:

$ sed -r 's/.*([0-9]+\.[0-9]+\.?[0-9]+)-.*/\1/' file
3.81
2.68
1.11.3

This will match version numbers with major, minor and build (optionally) marks, always followed by a hyphen.

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202