Count the number of digits in a bash variable

I have a number num=010. I would like to count the number of digits contained in this number. If the number of digits exceeds a certain number, I would like to do some processing.

In the above example, the number of digits is 3.

Thank!

+4
source share
5 answers

Assuming that the variable contains only numbers, the shell is already doing what you want here, with the extension length of the shell parameters .

$ var=012
$ echo "${#var}"
3
+10
source

In BASH, you can do this:

num='a0b1c0d23'
n="${num//[^[:digit:]]/}"
echo ${#n}
5

With awk you can:

num='012'
awk -F '[0-9]' '{print NF-1}' <<< "$num"
3

num='00012'
awk -F '[0-9]' '{print NF-1}' <<< "$num"
5

num='a0b1c0d'
awk -F '[0-9]' '{print NF-1}' <<< "$num"
3
+3
source

, x " "

chars=`echo -n $num | wc -c`
if [ $chars -gt $x ]; then
   ....
fi
+2

, :

ndigits=`echo $str | grep -P -o '\d' | wc -l`

:

$ echo sf293gs192 | grep -P -o '\d' | wc -l
       6
0

sed:

s="string934 56 96containing digits98w6"
num=$(echo "$s" |sed  's/[^0-9]//g')
echo ${#num}
10

grep:

s="string934 56 96containing digits98w6"
echo "$s" |grep -o "[0-9]" |grep -c ""
10
0

All Articles