计算 bash 变量中的位数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31327403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:18:51  来源:igfitidea点击:

Count the number of digits in a bash variable

bashshelldigits

提问by activelearner

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.

我有一个号码num=010。我想计算这个数字中包含的位数。如果位数超过某个数字,我想做一些处理。

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

在上面的例子中,位数是 3。

Thanks!

谢谢!

回答by Etan Reisner

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

假设变量只包含数字,那么 shell 已经用长度Shell Parameter Expansion做了你想要的。

$ var=012
$ echo "${#var}"
3

回答by anubhava

In BASH you can do this:

在 BASH 中,您可以这样做:

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

Using awk you can do:

使用 awk,您可以执行以下操作:

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

回答by EJK

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

假设变量 x 是问题中的“特定数字”

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

回答by Jason Hu

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

回答by Jahid

Using sed:

使用sed

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

Using grep:

使用grep

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