How to extract a number from a string using Bash example - LinuxConfig.org

Here a listed few of many ways how to extract number from a string. For all the examples below we will use sentence I am 999 years old. where the aim is to exctract nunber 999. Let's start by using tr command:
This is a companion discussion topic for the original entry at https://linuxconfig.org/how-to-extract-a-number-from-a-string-using-bash-example

this is a horrible example…
so many tutorials takes the simplest case and assume it’s a good enough answer.

This is school level kind of example here try this with your example:
TEST=$(echo “I am 99 years and 1 month old.” | tr -dc ‘0-9’)

you’ll see that you’ll get 991.

i know it says "get ‘a’ number from a string, but a good practice would build redundancy so that you can use only one line to do more work.

it’s like saying how can you multiply a number in bash:
2+2=4
:clap::clap::clap: good job you just multiplied 2 by 2.

I don’t have an answer just yet because once I get it I’ll post it here if I remember to do so.
it’s not that “I don’t know how to so I shouldn’t complain” it’s that I’m used to other languages then bash and feel like this is not very useful other then extracting numbers not “a” number.

I don’t want to be overly negative though, thanks for actually bothering to post this, but there’s another way that would extract all numbers form a string or file and then you’ll only need to select the one you need.
I feel mean complaining, but it’s true, you don’t need to learn how to add 2+2+2 if you could learn 2*3 :weary:

edit:

here you go:
TEST=(echo "I am 99 years and 1 month old." | tr '\n' ' ' | sed -e 's/[^0-9]/ /g' -e 's/^ *//g' -e 's/ *//g’ | tr -s ’ ’ | sed ‘s/ /\n/g’)

this separates the numbers with a space in the variable, or outputs them one by one in a file with a new line.

it’s not even what I’m looking for since I’m trying to put numbers in an array to do something else but it’s a better way of doing it, not a one liner, but thats the next answer I found on stackoverflow (sorry no link to the original answer because "new user can’t post link :+1:)