Regex in KornShell

silent1mezzo picture silent1mezzo · Jan 23, 2010 · Viewed 41.9k times · Source

I am trying to check whether a variable is exactly two numbers but I can not seem to figure it out.

How do you do check regular expressions (regex) in KornShell (ksh)?

I have tried:

if [[ $month =~ "[0-9]{2}" ]]
if [[ $month = _[0-9]{2}_ ]]

I have not been able to find any docs on it.

Any insight?

Answer

Alok Singhal picture Alok Singhal · Jan 23, 2010
case $month in
    [0-9][0-9]) echo "ok";;
    *) echo "no";;
esac

should work.

If you need full regexp search, you can use egrep like this:

if echo $month | egrep -q '^[0-9]{2}$'
then
    echo "ok"
else
    echo "no"
fi