How can we check if string is a version number or

2019-09-03 04:04发布

How to check if a string contains version in numberic/decimal format in shell script

for eg we have 1.2.3.5 or 2.3.5

What if we do not have a constraint on the number of characters we have in here. It could x.x.x.x or x.x as well.

标签: shell unix
4条回答
贼婆χ
2楼-- · 2019-09-03 04:42

Flip the logic: check if it contains an "invalid" character:

$ 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

Downside to this answer:

$ str=123....; [[ $str == *[^0-9.]* ]] && echo nope || echo yup
yup
查看更多
祖国的老花朵
3楼-- · 2019-09-03 04:48

If you're using bash, you can use the =~ regex match binary operator, for example:

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

For your particular test data, the following regex will do the trick:

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

(a number followed by any quantity of .<number> extensions) although, if you want to handle edge cases like 1.2-rc7 or 4.5-special, you'll need something a little more complex.

查看更多
一夜七次
4楼-- · 2019-09-03 04:52

Using bash regular expressions:

echo -n "Test: "
read i

if [[ $i =~ ^[0-9]+(\.[0-9]+){2,3}$ ]]; 
then
  echo Yes
fi

This accepts digits.digits.digits or digits.digits.digits.digits

Change {2,3} to shrink or enlarge the acceptable number of .digits (or {2,} for "at least 2")

  • ^ means beginning of string
  • [0-9]+ means at least one digit
  • \. is a dot
  • (...){2,3} accepts 2 or 3 of what's inside the ()
  • $ means end of string
查看更多
时光不老,我们不散
5楼-- · 2019-09-03 04:54

And if you're truly restricted to the Bourne shell, then use 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

I'm sure there are solutions involving awk or sed, but this will do.

查看更多
登录 后发表回答