j.lee
j.lee

Reputation: 651

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

What is the easiest way to do this in bash?

Thanks!

Upvotes: 6

Views: 20385

Answers (4)

Feriman
Feriman

Reputation: 627

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.

Upvotes: 6

kub1x
kub1x

Reputation: 3582

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'.

Upvotes: 12

anubhava
anubhava

Reputation: 786101

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

Upvotes: 4

ghostdog74
ghostdog74

Reputation: 343107

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

Upvotes: 2

Related Questions