Contents
How to extract number from string in bash shell
I will list some ways to extract number from string in bash shell script. We will set two sample variables to use with commands for extracting.
VAR1=”Im 25 years old.”
VAR2=”Im 25 years old. I have worked as system admin for 5 years.”
Four ways to extract number from string in bash shell
1. ‘tr’ command
# echo $VAR1 | tr -dc ‘0-9’ 25
# echo $VAR2 | tr -dc ‘0-9’ 255
2. ‘sed’ command
# echo $VAR1 | sed 's/[^0-9]*//g' 25
# echo $VAR2 | sed 's/[^0-9]*//g' 255
3. bash built-in
# echo “${VAR1//[!0-9]/}” 25
# echo “${VAR1//[!0-9]/}” 255
or
# echo “${VAR1//[^0-9]/}”
4. ‘grep’ command
# echo $VAR1 | grep -o -E '[0-9]+' 25
# echo $VAR2 | grep -o -E '[0-9]+' 25 5
May be we have more than ways better to extract number from string, if you know , please comment to share with me. Thank you.
Nguồn: https://cuongquach.com/