octosquidopus
octosquidopus

Reputation: 3713

sed Extract version number from string (only version, without other numbers)

I want to achieve the same as explained in sed: Extract version number from string, but taking into consideration only the first sequence of numbers or even safer, tell sed to keep only the sequence of numbers following the name of the command, leaving out the rest.

I have: Chromium 12.0.742.112 Ubuntu 11.04

I want: 12.0.742.112

Instead of: 12.0.742.11211.04

I now know that using head or tail with sort it is possible to display the largest/smallest number, but how can I tell sed to consider the first sequence only?

EDIT: I forgot to mention that I'm using bash.

Upvotes: 4

Views: 18700

Answers (6)

Magnus
Magnus

Reputation: 31

This will match/output the first occurance of number(s) and dot(s):

sed -rn "s/([^0-9]*)([0-9\.]+)([^0-9]*.*)/\2/ p"

I've thrown a couple of narly strings at it and it held water :)

Upvotes: 0

Kusalananda
Kusalananda

Reputation: 15603

Here's a solution that doesn't rely on the position of the command in your string, but that will pick up whatever comes after it:

command="Chromium"

string1="Chromium 12.0.742.112 Ubuntu 11.04"
string2="Ubuntu 11.04 Chromium 12.0.742.112"

echo ${string1} | sed "s/.*${command} \([^ ]*\).*$/\1/"
echo ${string2} | sed "s/.*${command} \([^ ]*\).*$/\1/"

Upvotes: 4

bash-o-logist
bash-o-logist

Reputation: 6911

well, if you are using bash, and if what you want is always on 2nd field,

$ string="Chromium 12.0.742.112 Ubuntu 11.04"
$ set -- $string; echo $2
12.0.742.112

Upvotes: 1

Beta
Beta

Reputation: 99084

The first number? How about:

sed 's/[^0-9.]*\([0-9.]*\).*/\1/'

Upvotes: 18

Dov Grobgeld
Dov Grobgeld

Reputation: 4983

The following perl command does it:

echo "Chromium 12.0.742.112 Ubuntu 11.04" | perl -ne '/[\d\.]+/ && print $&'

Upvotes: 0

Kusalananda
Kusalananda

Reputation: 15603

With cut (assuming you always want the second bit of info on the line):

$ echo "Chromium 12.0.742.112 Ubuntu 11.04" | cut -d' ' -f2
12.0.742.112

Upvotes: 1

Related Questions