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.
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.
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 stringIf 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.
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.
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