如何确定字符串在ksh中是否为数字

时间:2012-02-09 18:51:36

标签: shell ksh

我正在尝试验证ksh中的输入,并想知道确定字符串是否为有效数字的最简单方法。

6 个答案:

答案 0 :(得分:7)

快来:

    case $INPUT in
        +([0-9])*(.)*([0-9]) )
              # Variable is numeric
              ;;
        *) 
              # Nope, not numeric
              ;;

esac

答案 1 :(得分:1)

这修复了FreudianSlip的答案,包括可选的,带“ - ”或“+”符号,允许以“。”开头的十进制数字。 (无前导0),并排除包含多个“。”的数字。 (例如“12 ...... 34”):

case $INPUT in
    {,1}([-+])+([0-9]){,1}(.)*([0-9])|{,1}([-+]).+([0-9]))
          # Variable is numeric
          ;;
    *) 
          # Nope, not numeric
          ;;

esac

答案 2 :(得分:1)

我在这里看到了这个答案(https://www.unix.com/302299284-post9.html),它在Solaris 10中的ksh-88中用于整数:

x=2763
if [[ $x == +([0-9]) ]]; then
    print integer
else
    print nope
fi

答案 3 :(得分:0)

[ $input -ge 0 -o $input-lt 0 ] 2>/dev/null && echo "numeric"

这将检查输入是否为数字(正整数或负整数),如果是,则打印数字。

答案 4 :(得分:0)

更简单,如果您只想知道字符串是否由数字组成:

case $INPUT in
    [0-9][0-9]* )
          # Variable contains only digits
          ;;
    *) 
          # Variable contains at least one non-digit
          ;;
esac

答案 5 :(得分:0)

您可以在测试中使用字符串运算符,如下所示:

if [[ "${input%%*( )+([0-9])?(.)*([0-9])}" = "" ]]; then
   print "Is numeric"
fi
相关问题