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!
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!
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
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
Assuming that the variable x is the "certain number" in the question
chars=`echo -n $num | wc -c`
if [ $chars -gt $x ]; then
....
fi
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
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