How to extract a number from a string using Bash example

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:

$ NUMBER=$(echo "I am 999 years old." | tr -dc '0-9')
$ echo $NUMBER
999

Next, we use sed command:

$ NUMBER=$(echo "I am 999 years old." | sed 's/[^0-9]*//g')
$ echo $NUMBER
999

Using bash only:

$ STRING="I am 999 years old."
$ echo "${STRING//[!0-9]/}"
999
OR
$ echo "${STRING//[^0-9]/}"

In the next example we will use grep to extract number from string:

$ NUMBER=$(echo "I am 999 years old." | grep -o -E '[0-9]+')
$ echo $NUMBER
999


Comments and Discussions
Linux Forum