Skip to content
Advertisement

how to extract only numbers from variable and I need to give spaces between those numbers?

This is the sample string variable:

str="A=30|B='(if a=45 then b=100 else b=101)'|C=1000"

Required output is:

30 45 100 101 1000

I had tried below regex but I did not get proper output:

v=$(echo "$str" | sed 's/[^0-9]*//g'|wc -w)

Let me know proper statement for getting above output.

Advertisement

Answer

Looks like you want the number of numbers in the string.

With GNU awk:

gawk '{print NF}' FPAT='[[:digit:]]+' <<< "${str}"

With GNU grep and wc:

grep -Eo '[[:digit:]]+' <<< "${str}" | wc -w

Or with sed and `wc (works on all platforms):

sed -E 's/[^[:digit:]]*([[:digit:]]+)/1 /g' <<< "${str}" | wc -w

or (simpler):

sed -E 's/[^0-9]+/ /g' <<< "${str}" | wc -c
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement