Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of digits in a bash variable

Tags:

bash

shell

digits

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!

like image 482
activelearner Avatar asked Jul 09 '15 20:07

activelearner


People also ask

How do I count characters in a variable bash?

you can use wc to count the number of characters in the file wc -m filename.

How do I count numbers in bash?

The recommended way to evaluate arithmetic expressions with integers in Bash is to use the Arithmetic Expansion capability of the shell. The builtin shell expansion allows you to use the parentheses ((...)) to do math calculations. The format for the Bash arithmetic expansion is $(( arithmetic expression )) .

How do you count a number in a string in bash?

The most commonly used and simple way to count the length of a string is to use “#” symbol. The following commands will assign a value to the variable, $string and print the total number of characters of $string.


4 Answers

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
like image 83
Etan Reisner Avatar answered Oct 12 '22 12:10

Etan Reisner


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
like image 33
anubhava Avatar answered Oct 12 '22 11:10

anubhava


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

chars=`echo -n $num | wc -c`
if [ $chars -gt $x ]; then
   ....
fi
like image 45
EJK Avatar answered Oct 12 '22 12:10

EJK


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
like image 42
Jason Hu Avatar answered Oct 12 '22 12:10

Jason Hu