开发者

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="somethi开发者_如何学Pythonng34521.32somethingmore3241"

Output I want is 34521

What is the easiest way to do this in 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.

I sometimes like to use @ instead of the classical / in the sed replace 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'.


There's the awk solution:

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.


This sed 1 liner will do the job I think:

str="something34521.32somethingmore3241"
echo $str | sed -r 's/^([^.]+).*$/\1/; s/^[^0-9]*([0-9]+).*$/\1/'
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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜