tags:

views:

179

answers:

3

I'm reading a number from a file using

x= egrep "(^[0-9][0-9])" temp1

but when I use these numbers in a case statement it always fails:

case $x in
[0-9])
  statements;;
[0-9][0-9]
  statements;;
esac

when I echo the number it looks fine, I'm not sure why it is not working.

+1  A: 

The bourne / bash case-statement matches the entire string, while egrep (in your example) is matching only the leading characters.

In your example, you would change your case-statement to be:

case "$x" in
[0-9][0-9]*)
  statements;;
[0-9]*)
  statemtns;;
*)
  statements for unmatched....
esac

Note that I reversed the order, because the first match will take effect. Also, I quoted the $x because I am paranoid ;) You can leave out the quotes on $x if it might have leading blanks you want to ignore.

  • Greg
Gregor
A: 

The space after the equal sign and no process substitution makes x empty. This may be why your case isn't working.

You can use the -o option to egrep to make sure you get only the string you're interested in.

x=$(egrep -o "(^[0-9][0-9])" temp1)

case $x in
[0-9])
  statements;;
[0-9][0-9]
  statements;;
esac
Dennis Williamson
A: 

depending on what you want to do, you can do it with awk

awk '/^[0-9][0-9]/'{
  #do something
}' temp1

or with bash

while read -r line
do
  case $line in 
    [0-9][0-9]* ) echo "do something ;;
    [0-9]* ) echo "do something";;
    * ) echo "do something";;
  esac
done <"temp1"
ghostdog74