Bash脚本:测试浮点数是否在某个范围内,包括负数

问题描述 投票:2回答:2

我试图测试变量$test是否介于-0.90.9之间。以下代码适用于数字,但如果$test是小写字母,则表示它是-0.90.9之间的数字。

有没有更好的方法来做到这一点,所以字母不被认为是在范围内?

test=a

if (( $( echo "$test >= -0.9" |bc -l) )) && (( $(echo "$test <= 0.9" |bc -l) )); then
    echo "${test} is between -0.9 and 0.9"
else
    echo "${test} is NOT between -0.9 and 0.9"
fi
bash comparison bc
2个回答
1
投票

更换:

if (( $( echo "$test >= -0.9" |bc -l) )) && (( $(echo "$test <= 0.9" |bc -l) )); then

使用(假设GNU或其他增强的bc):

if [[ "$test" =~ ^[[:digit:].e+-]+$ ]] && echo "$test>-0.9 && $test <=0.9" |bc -l | grep -q 1; then

How it works

  • [[ "$test" =~ ^[[:digit:].e+-]+$ ]] 这将检查$test是否仅包含合法的数字字符。
  • && 只有当$test通过了数字检查时,才会继续进行bc测试。
  • echo "$test>-0.9 && $test <=0.9" |bc -l | grep -q 1 这将验证$test是否在您想要的范围内。 grep -q 1if语句设置适当的退出代码。

0
投票

重构代码以使用Awk可能更有效,尽管它需要了解有关shell的一些模糊的东西。

if awk -v number="$test" 'END { exit !( \
    number !~ /[^0-9.]/ && number !~ /\..*\./ && \
    number >= -0.9 && number <= 0.9) }' /dev/null
then
    echo "$test is between -0.9 and 0.9"
else
    echo "$test is NOT between -0.9 and 0.9"
fi

if检查的退出代码如果为零则视为真,这与括号内的真值相反;因此exit !(...)。 Awk的处理模型要求您读取输入文件;我们提供/dev/null,并将实际逻辑放在END块中,以便即使没有输入也会执行。

这将检查是否存在多于一个小数点,但正则表达式当前不能处理指数表示法。考虑到John1024的答案中的正则表达式,添加对此的支持应该不会太难。

© www.soinside.com 2019 - 2024. All rights reserved.