12

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

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

Thanks!

jww
  • 97,681
  • 90
  • 411
  • 885
activelearner
  • 7,055
  • 20
  • 53
  • 94

5 Answers5

21

Assuming the variable only contains digits then the shell already does what you want here with the length Shell Parameter Expansion.

$ var=012
$ echo "${#var}"
3
Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
  • This doesn't work if `var` is assigned the result of a command; instead it returns the length of the command. Instead use the answer from @anubhava – Peter Kionga-Kamau Jan 12 '23 at 22:07
11

In BASH you can do this:

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

Using awk you can do:

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
3

Assuming that the variable x is the "certain number" in the question

chars=`echo -n $num | wc -c`
if [ $chars -gt $x ]; then
   ....
fi
EJK
  • 12,332
  • 3
  • 38
  • 55
2

this work for arbitrary string mixed with digits and non digits:

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

demo:

$ echo sf293gs192 | grep -P -o '\d' | wc -l
       6
Jason Hu
  • 6,239
  • 1
  • 20
  • 41
1

Using sed:

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

Using grep:

s="string934 56 96containing digits98w6"
echo "$s" |grep -o "[0-9]" |grep -c ""
10
Jahid
  • 21,542
  • 10
  • 90
  • 108