我正在尝试验证 ksh 中的输入,并且想知道确定字符串是否为有效数字的最简单方法。
尝试一下:
case $INPUT in
+([0-9])*(.)*([0-9]) )
# Variable is numeric
;;
*)
# Nope, not numeric
;;
esac
更简单,如果你只想知道字符串是否由数字组成:
case $INPUT in
[0-9][0-9]* )
# Variable contains only digits
;;
*)
# Variable contains at least one non-digit
;;
esac
我在这里看到了这个答案(https://www.unix.com/302299284-post9.html)并且它确实适用于 Solaris 10 中的 ksh-88 对于整数:
x=2763
if [[ $x == +([0-9]) ]]; then
print integer
else
print nope
fi
这修复了 FreudianSlip 的答案,包括可选的前导“-”或“+”符号,允许以“.”开头的十进制数字。 (无前导 0),并排除包含多个“.”的数字。 (例如“12...34”):
case $INPUT in
{,1}([-+])+([0-9]){,1}(.)*([0-9])|{,1}([-+]).+([0-9]))
# Variable is numeric
;;
*)
# Nope, not numeric
;;
esac
您可以在测试中使用字符串运算符,如下所示:
if [[ "${input%%*( )+([0-9])?(.)*([0-9])}" = "" ]]; then
print "Is numeric"
fi
[ $input -ge 0 -o $input-lt 0 ] 2>/dev/null && echo "numeric"
这将检查输入是否为数字(正整数或负整数),如果是则打印数字。
if [[ -z $(print $input | tr -d '[:digit:]') ]]
then
print "$input is numeric"
fi
-z 测试运算符测试空字符串。
tr -d
命令删除所有数字。
如果 tr 之后还有任何内容,则它不是数字。