简体   繁体   English

如何在 Bash 中搜索小数点后的浮点数?

[英]How to search numbers after decimal point for floating point number in Bash?

I am messing around with something on bash (I am very new to it).我正在弄乱 bash 上的一些东西(我对它很陌生)。

I have a floating point number.我有一个浮点数。

I want to to be able to check if there is any digits after the decimal point from 1-9 in order to determine whether it is a whole number - and do it within an if-else statement.我希望能够检查 1-9 的小数点后是否有任何数字以确定它是否是整数 - 并在 if-else 语句中执行。

for example例如

if(*number does have a 1-9 digit after decimal*)
then
    echo 'Number is not a whole number'
else
    echo 'Number is a whole number'
fi

Dabbled with grep and REGEX but don't have a great grasp of it yet涉足 grep 和 REGEX 但还没有很好地掌握它

Mac_3.2.57$cat findWhole.bash
#!/bin/bash
for x in 1.123456789 0001230045600.00 1.000000 1 1. 1.. 0002 .00 22.00023400056712300 1.00 .
do
  if [[ "$x" =~ ^[0-9]*\.[0-9]*[1-9][1-9]*[0-9]*$ ]]; then
    echo "$x is not a whole number"
  elif [[ "$x" =~ ^[0-9][0-9]*\.?0*$|^\.00*$ ]]; then
    echo "$x is a whole number"
  else
    echo "$x is not a number"
  fi
done
Mac_3.2.57$./findWhole.bash
1.123456789 is not a whole number
0001230045600.00 is a whole number
1.000000 is a whole number
1 is a whole number
1. is a whole number
1.. is not a number
0002 is a whole number
.00 is a whole number
22.00023400056712300 is not a whole number
1.00 is a whole number
. is not a number
Mac_3.2.57$

With a regex:使用正则表达式:

x=1.123456789
if [[ "$x" =~ \.[0-9]{1,9}$ ]]; then
  echo 'Number is not a whole number'
else
  echo 'Number is a whole number'
fi

Output:输出:

Number is not a whole number

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM