Regular expressions

Derek Ragona derek at computinginnovations.com
Sat Aug 18 11:13:18 PDT 2007


At 12:04 PM 8/18/2007, Christer Hermansson wrote:
>Hi.
>
>I'm trying to use regular expressions inside a shell script (/bin/sh) on 
>my freebsd box and can't get it to work so I searched the web  and found 
>http://regexlib.com/RETester.aspx
>
>On this webpage I could test my pattern "^[A-Za-z0-9_-]+$" and everything 
>was fine, did exactly what I wanted to do, check that a string only 
>contains some combination of the characters A-Z, a-z, 0-9, hyphen - and 
>underscore _.
>
>I also found some basic example at 
>http://www.grymoire.com/Unix/Sh.html#uh-88 :
>
>--------8<--------8<--------8<--------8<--------8<--------
>
>#!/bin/sh
>
>echo "Type in a number"
>read ans
>number=`expr "$ans" : "([0-9]*)"`
>if [ "$number" != "$ans" ]; then
>echo "Not a number"
>elif [ "$number" -eq 0 ]; then
>echo "Nothing was typed"
>else
>echo "$number is a fine number"
>fi
>
>--------8<--------8<--------8<--------8<--------8<--------
>
>The above example doesn't work on my freebsd box. Maybe I need to update 
>my system, sitting with 6.0R which never been updated.
>
>Is there anyone who has some advice about how to get regular expressions 
>to work in FreeBSD shell script ?
>
>--
>
>Christer Hermansson

You have a syntax error using expr.  Do a man on expr for more details but 
if you change that line from:
number=`expr "$ans" : "([0-9]*)"`
to:
number=`expr "$ans" : "\([0-9]*\)"`

You will get the desired results.

Also when debugging scripts remember to add:
set -x
to your script on the second line, and see what the script lines are 
actually doing.

         -Derek

-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.
MailScanner thanks transtec Computers for their support.



More information about the freebsd-questions mailing list