Skip to content
TrySitePrice

Bash Shell: Extract Digits From a String

Best/Tutorial

If you want to extract digits from a string in bash, you can use the following methods:

  1. Using grep:

string="abc123def456"

digits=$(echo $string | grep -o '[0-9]\+')

echo $digits

Output:

123456

  1. Using sed:

string="abc123def456"

digits=$(echo $string | sed 's/[^0-9]*//g')

echo $digits

Output:

123456

  1. Using awk:

string="abc123def456"

digits=$(echo $string | awk '/[0-9]+/{ gsub(/[^0-9]+/, "", $0); print $0 }')

echo $digits

Output:

123456

These methods use regular expressions to match sequences of digits in the input string, and extract them to a new string.