bash 从字符串中提取第一个数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5811753/
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
extract the first number from a string
提问by j.lee
I want to extract the first number from a given string. The number is a float but I only need the integers before the decimal.
我想从给定的字符串中提取第一个数字。该数字是一个浮点数,但我只需要小数点前的整数。
example:
例子:
string1="something34521.32somethingmore3241"
Output I want is 34521
我想要的输出是 34521
What is the easiest way to do this in bash?
在 bash 中执行此操作的最简单方法是什么?
Thanks!
谢谢!
回答by anubhava
This sed 1 liner will do the job I think:
这个 sed 1 liner 可以完成我认为的工作:
str="something34521.32somethingmore3241"
echo $str | sed -r 's/^([^.]+).*$//; s/^[^0-9]*([0-9]+).*$//'
输出
34521
回答by ghostdog74
You said you have a string and you want to extract the number, i assume you have other stuff as well.
你说你有一个字符串并且你想提取这个数字,我想你还有其他的东西。
$ echo $string
test.doc_23.001
$ [[ $string =~ [^0-9]*([0-9]+)\.[0-9]+ ]]
$ echo "${BASH_REMATCH[1]}"
23
$ foo=2.3
$ [[ $string =~ [^0-9]*([0-9]+)\.[0-9]+ ]]
$ echo "${BASH_REMATCH[1]}"
2
$ string1="something34521.32somethingmore3241"
$ [[ $string1 =~ [^0-9]*([0-9]+)\.[0-9]+ ]]
$ echo "${BASH_REMATCH[1]}"
34521
回答by kub1x
So just for simplicity I'll post what I was actually looking for when I got here.
因此,为了简单起见,我将发布我到达这里时实际寻找的内容。
echo $string1 | sed 's@^[^0-9]*\([0-9]\+\).*@@'
Simply skip whatever is not a number from beginning of the string ^[^0-9]*, then match the number \([0-9]\+\), then the rest of the string .*and print only the matched number \1.
简单地从字符串的开头跳过不是数字的任何内容^[^0-9]*,然后匹配数字\([0-9]\+\),然后匹配字符串的其余部分.*并仅打印匹配的数字\1。
I sometimes like to use @instead of the classical /in the sedreplace expressions just for better visibility within all those slashes and backslashes. Handy when working with paths as you don't need to escape slashes. Not that it matters in this case. Just sayin'.
我有时喜欢在替换表达式中使用@而不是经典/,sed只是为了在所有这些斜杠和反斜杠中更好地可见。使用路径时很方便,因为您不需要转义斜杠。在这种情况下,这并不重要。只是在说'。

