简体   繁体   English

从字符串中提取第一个数字

[英]extract the first number from a string

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 Output 我要的是34521

What is the easiest way to do this in bash?在 bash 中执行此操作的最简单方法是什么?

Thanks!谢谢!

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]\+\).*@\1@'

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]\+\) ,然后匹配字符串.*的 rest 并仅打印匹配的数字\1

I sometimes like to use @ instead of the classical / in the sed replace expressions just for better visibility within all those slashes and backslashes.我有时喜欢在sed替换表达式中使用@而不是经典的/ ,只是为了在所有这些斜杠和反斜杠中获得更好的可见性。 Handy when working with paths as you don't need to escape slashes.使用路径时很方便,因为您不需要转义斜线。 Not that it matters in this case.在这种情况下,这并不重要。 Just sayin'.只是在说'。

This sed 1 liner will do the job I think:这个 sed 1 班轮将完成我认为的工作:

str="something34521.32somethingmore3241"
echo $str | sed -r 's/^([^.]+).*$/\1/; s/^[^0-9]*([0-9]+).*$/\1/'
OUTPUT OUTPUT
 34521

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

There's the awk solution:有 awk 解决方案:

echo $string1 | awk -F'[^0-9]+' '{ print $2 }'

Use -F'[^0-9,]+' to set the field separator to anything that is not a digit (0-9) or a comma, then print it.使用 -F'[^0-9,]+' 将字段分隔符设置为不是数字 (0-9) 或逗号的任何内容,然后打印它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM