case command and regex
Daniel Wayne Armstrong
daniel-HRJVlgn2G/y5aS82P/H3Zg at public.gmane.org
Sun Mar 17 03:54:59 UTC 2013
On Sat, Mar 16, 2013 at 10:53 PM, William Park <opengeometry-FFYn/CNdgSA at public.gmane.org> wrote:
> On Sat, Mar 16, 2013 at 08:15:49PM -0400, Daniel Wayne Armstrong wrote:
>> I am trying to write a usable regex for the case command in a shell
>> script. For example:
>>
>> ---
>>
>> #!/bin/bash
>> # testscript $1
>> if [[ $1 =~ [\+\-]([0-9]+)+$ ]]; then
>> echo "Match is $1"
>> else
>> echo "No match."
>> fi
>>
>> while [ $# -gt 0 ]; do
>> case $1 in
>> [\+\-]\([0-9]+\)+$ ) echo "Match is $1"
>> exit
>> ;;
>> * ) echo "No match."
>> exit
>> ;;
>> esac
>> done
>>
>> ---
>>
>> ... and if I run "./testscript +77" I get:
>>
>> Match is +77
>> No match.
>>
>> I know I have the syntax messed up somehow in the case regex example
>> but I have tried it many different ways and can't seem to get it
>> right. I have tried extglob as well and no joy.
>>
>> If anyone could see what I am missing it would be greatly appreciated!
>> Thanks!
>
> Case statement takes glob(7) pattern, not regular expression. Well,
> 'extglob' is in the right direction. Try
>
> case $1 in
> [+-]+([0-9]) ) echo "Match is $1" ;;
> * ) echo "No match." ;;
> esac
Thanks William and Chris! The point about globbing narrowed my search and:
shopt -s extglob
case $1 in
[+-]+([0-9]) ) echo "Match is $1" ;;
* ) echo "No match." ;;
esac
... indeed works as desired. I was jumbling up the regex and globbing
earlier ... the manpage was a help as well as this LJ article:
http://www.linuxjournal.com/content/bash-extended-globbing
--
(o< .: per curiositas ad astra .: http://www.circuidipity.com
(/)_
--
The Toronto Linux Users Group. Meetings: http://gtalug.org/
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://gtalug.org/wiki/Mailing_lists
More information about the Legacy
mailing list