How to extract numbers from a string?
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