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 h开发者_开发知识库ead 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.
The first number? How about:
sed 's/[^0-9.]*\([0-9.]*\).*/\1/'
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/"
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
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
The following perl command does it:
echo "Chromium 12.0.742.112 Ubuntu 11.04" | perl -ne '/[\d\.]+/ && print $&'
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 :)
精彩评论