tags:

views:

373

answers:

4

I'm trying to check whether a variable is exactly 2 numbers but I can't seem to figure it out.

How do you do check regular expressions in KSH?

I've tried

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

I haven't been able to find any docs on it

+3  A: 
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
Alok
A: 

you can try this as well

$ month=100
$ [[ $month == {1,2}([0-9]) ]] && echo "ok" || echo "no"
no
$ [[ $month == [0-9][0-9] ]] && echo "ok" || echo "no"
no
$ month=10
$ [[ $month == {1,2}([0-9]) ]] && echo "ok" || echo "no"
ok
$ [[ $month == [0-9][0-9] ]] && echo "ok" || echo "no"
ok
ghostdog74
A: 

Where I come from, this is more likely to validate numeric months:

if (( $month >= 1 && $month <= 12 ))

or

[[ $month =~ ^([1-9]|1[012])$ ]]

or to include a leading zero for single-digit months:

[[ $month =~ ^(0[1-9]|1[012])$ ]]
Dennis Williamson
A: 

ksh does not use regular expressions; it uses a simpler but still quite useful language called "shell globbing patterns". The key ideas are

  • Classes like [0-9] or [chly] match any character in the class.
  • The . is not a special character; it matches only ..
  • The ? matches any single character.
  • The * matches any sequence of characters.
  • Unlike regular expressions, shell globbing patterns must match the entire word, so it works as if it were a regexp it would always start with ^ and end with $.

Globbing patterns are not as powerful as regular expressions, but they are much easier to read, and they are very convenient for matching filenames and simple words. The case construct is my favorite for matching but there are others.

As already noted by Alok you probably want

case $number in
  [0-9][0-9]) success ;;
  *) failure;;
esac

Although possibly you might prefer not to match a two-digit number with initial zero, so prefer [1-9][0-9].

Norman Ramsey

related questions