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
ARE YOU LOOKING FOR A LINUX JOB?
Submit your RESUME, create a JOB ALERT or subscribe to RSS feed on LinuxCareers.com.
LINUX CAREER NEWSLETTER
Subscribe to NEWSLETTER and receive latest news, jobs, career advice and tutorials.
DO YOU NEED ADDITIONAL HELP?
Get extra help by visiting our LINUX FORUM or simply use comments below.

You may also be interested in:



Comments and Discussions