我们如何检查字符串是否是版本号

时间:2013-06-12 01:28:50

标签: shell unix

如何在shell脚本

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

例如我们有1.2.3.5或2.3.5

如果我们对此处的字符数没有限制,该怎么办?它也可以是x.x.x.x或x.x.

4 个答案:

答案 0 :(得分:3)

如果您使用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等边缘情况,则需要更复杂的东西。

答案 1 :(得分:1)

使用bash regular expressions

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个内容
  • $表示字符串结尾

答案 2 :(得分:0)

如果你真的受限于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的解决方案,但这样做。

答案 3 :(得分:-2)

翻转逻辑:检查它是否包含“无效”字符:

$ 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