4

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.

0

6 Answers 6

18

The first number? How about:

sed 's/[^0-9.]*\([0-9.]*\).*/\1/'
Sign up to request clarification or add additional context in comments.

3 Comments

If someone reaches here looking for extracting 1.1.1 from v1.1.1, then you can use sed 's/v\(.*\)/\1/' github.com/ssi-anik/medium-unlimited/blob/…
@ssi-anik: or s/.//
Makes sense, didn't think about it tho. :D
4

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/"

Comments

1

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

5 Comments

Well no, sometimes the version precedes the name
@octosquidopus, so, how do we know which version you want?
I want the number following the name of the command, or if not present, the first number displayed.
@octosquidopus How do we know what the name of the command is?
Since it's in a script, it can be previously stored in a variable. But anyway, it doesn't really matter what's the name of the command, as long as non-numbers preceding the version are removed.
1

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

Comments

0

The following perl command does it:

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

Comments

0

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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.