Issue
I have version numbers that look like this:
11.22.33
11.22.33-alpha
11.22.33-beta
11.22.33-beta2
But I need to reject versions with uppercase characters, e.g.
11.22.33-ALPHA (bad uppercase)
11.22.33-alpha-1 (bad char '-')
I must use egrep.
Here's an example in bash
version=11.22.33-BETA
result=$(echo $version | egrep "[[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+(-[0-9a-z]+)?"); echo $result
if [[ -z $result ]]; then
echo "BAD version!!!"
else
echo "Good version."
fi
This code doesn't work and outputs "BAD version", with result containing "11.22.33-BETA". What do I need to change?
Solution
egrep
has been deprecated.
You may use this regex in grep -E
:
grep -E '^[[:digit:]]+(\.[[:digit:]]+){2}(-[a-z]+[[:digit:]]*)?$' file
11.22.33
11.22.33-alpha
11.22.33-beta
11.22.33-beta2
Note use of anchors and quantifiers.
RegEx Details:
^
: Start[[:digit:]]+
: Match 1+ digits(\.[[:digit:]]+){2}
: Match dot followed by 1+ digits. Repeat this group 2 times(
: Start a group-
: Match a-
[a-z]+
: Match 1+ lowercase letters[[:digit:]]*
: Match 0 or more digits
)?
: End group.?
makes this optional match$
End
You bash
script could be like this using -q
(quiet) option in grep
. Note how we avoid creating a shell variable to store output of grep
.
if grep -qE '^[[:digit:]]+(\.[[:digit:]]+){2}(-[a-z]+[[:digit:]]*)?$' <<< "$version"
then
echo "Good version."
else
echo "Bad version."
fi
Answered By - anubhava Answer Checked By - Dawn Plyler (WPSolving Volunteer)