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!
you can use wc to count the number of characters in the file wc -m filename.
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 )) .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With