bash sed 从字符串中提取版本号(只有版本,没有其他数字)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7516455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sed Extract version number from string (only version, without other numbers)
提问by octosquidopus
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.
我想实现与sed 中解释的相同:从 string 中提取版本号,但只考虑第一个数字序列或更安全,告诉 sed 只保留命令名称后面的数字序列,省略休息。
I have:Chromium 12.0.742.112 Ubuntu 11.04
I have:铬 12.0.742.112 Ubuntu 11.04
I want:12.0.742.112
I want:12.0.742.112
Instead of:12.0.742.11211.04
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?
我现在知道使用 head 或 tail 进行排序可以显示最大/最小的数字,但是我如何告诉 sed 只考虑第一个序列?
EDIT: I forgot to mention that I'm using bash.
编辑:我忘了提到我正在使用 bash。
回答by Beta
The first number? How about:
第一个数字?怎么样:
sed 's/[^0-9.]*\([0-9.]*\).*//'
回答by Kusalananda
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} \([^ ]*\).*$//"
echo ${string2} | sed "s/.*${command} \([^ ]*\).*$//"
回答by Kusalananda
With cut(assuming you always want the second bit of info on the line):
与cut(假设您总是想要在线的第二位信息):
$ echo "Chromium 12.0.742.112 Ubuntu 11.04" | cut -d' ' -f2
12.0.742.112
回答by bash-o-logist
well, if you are using bash, and if what you want is always on 2nd field,
好吧,如果您使用的是 bash,并且您想要的总是在第二场,
$ string="Chromium 12.0.742.112 Ubuntu 11.04"
$ set -- $string; echo
12.0.742.112
回答by Dov Grobgeld
The following perl command does it:
以下 perl 命令执行此操作:
echo "Chromium 12.0.742.112 Ubuntu 11.04" | perl -ne '/[\d\.]+/ && print $&'

