【问题标题】:Bash script: testing if floating point number is in a certain range including negative numbersBash脚本:测试浮点数是否在一定范围内,包括负数
【发布时间】:2017-12-15 02:23:38
【问题描述】:

我正在尝试测试变量$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


    【解决方案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
    

    工作原理

    • [[ "$test" =~ ^[[:digit:].e+-]+$ ]]

      这会检查$test 是否只包含合法的数字字符。

    • &amp;&amp;

      仅当$test 通过号码检查时,才会继续 bc 测试。

    • echo "$test&gt;-0.9 &amp;&amp; $test &lt;=0.9" |bc -l | grep -q 1

      这将验证$test 在您想要的范围内。 grep -q 1 为要使用的 if 语句设置适当的退出代码。

    【讨论】:

      【解决方案2】:

      重构代码以使用 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检查的退出码如果为0,则认为为真,与括号内的真值相反;因此exit !(...)。 awk 的处理模型需要你读取一个输入文件;我们提供/dev/null,并将实际逻辑放在END 块中,这样即使没有输入也能执行。

      这会检查小数点不超过一位,但正则表达式目前无法处理指数表示法。鉴于 John1024 回答中的正则表达式,添加对此的支持应该不会太难。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-12-14
        • 2018-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多