如何检查string是否是版本号?



如何在shell脚本中检查字符串是否包含数字/十进制格式的版本

例如,我们有1.2.3.5或2.3.5

如果我们对这里的字符数没有限制怎么办?也可以是x.x.x.x或x.x。

如果您使用bash,您可以使用=~正则表达式匹配二进制运算符,例如:

pax> if [[ 1.x20.3 =~ ^[0-9]+.[0-9]+.[0-9]+$ ]] ; then echo yes ; fi
pax> if [[ 1.20.3 =~ ^[0-9]+.[0-9]+.[0-9]+$ ]] ; then echo yes ; fi
yes

对于您的特定测试数据,下面的正则表达式将会奏效:

^[0-9]+(.[0-9]+)*$

(一个数字后面跟着任意数量的.<number>扩展),尽管,如果您想处理边缘情况,如1.2-rc74.5-special,您将需要一些更复杂的东西。

使用bash正则表达式:
echo -n "Test: "
read i
if [[ $i =~ ^[0-9]+(.[0-9]+){2,3}$ ]]; 
then
  echo Yes
fi

接受digits.digits.digitsdigits.digits.digits.digits

更改{2,3}以缩小或扩大.digits的可接受数量(或{2,}为"至少2")

  • ^表示字符串
  • 的开头
  • [0-9]+表示至少一个数字
  • .是一个点
  • (...){2,3}接受()
  • 中的2或3个内容
  • $表示字符串结束

如果你真的受限于Bourne shell,那么使用expr:

if expr 1.2.3.4.5 : '^[0-9][.0-9]*[0-9]$' > /dev/null; then
  echo "yep, it's a version number"
fi

我相信有涉及awk或sed的解决方案,但这将做。

翻转逻辑:检查是否包含"invalid"字符:

$ str=1.2.3.4.5; [[ $str == *[^0-9.]* ]] && echo nope || echo yup
yup
$ str=123x4.5;   [[ $str == *[^0-9.]* ]] && echo nope || echo yup
nope

这个答案的缺点:

$ str=123....; [[ $str == *[^0-9.]* ]] && echo nope || echo yup
yup

最新更新