How to extract numbers from a string? How to extract numbers from a string? bash bash

How to extract numbers from a string?


You can use tr to delete all of the non-digit characters, like so:

echo toto.titi.12.tata.2.abc.def | tr -d -c 0-9


To extract all the individual numbers and print one number word per line pipe through -

tr '\n' ' ' | sed -e 's/[^0-9]/ /g' -e 's/^ *//g' -e 's/ *$//g' | tr -s ' ' | sed 's/ /\n/g'

Breakdown:

  • Replaces all line breaks with spaces: tr '\n' ' '
  • Replaces all non numbers with spaces: sed -e 's/[^0-9]/ /g'
  • Remove leading white space: -e 's/^ *//g'
  • Remove trailing white space: -e 's/ *$//g'
  • Squeeze spaces in sequence to 1 space: tr -s ' '
  • Replace remaining space separators with line break: sed 's/ /\n/g'

Example:

echo -e " this 20 is 2sen\nten324ce 2 sort of" | tr '\n' ' ' | sed -e 's/[^0-9]/ /g' -e 's/^ *//g' -e 's/ *$//g' | tr -s ' ' | sed 's/ /\n/g'

Will print out

2023242


Here is a short one:

string="toto.titi.12.tata.2.abc.def"id=$(echo "$string" | grep -o -E '[0-9]+')echo $id // => output: 12 2

with space between the numbers.Hope it helps...