Reputation: 19870
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.
Upvotes: 3
Views: 478
Reputation: 85883
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.
Upvotes: 1
Reputation: 195269
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
Upvotes: 8