tags:

views:

570

answers:

3

I’m trying to validate input by using egrep and regex.Here is the line from script (c-shell):

echo $1 | egrep '^[0-9]+$'
if ($status == 0) then
set numvar = $1
else
    echo "Invalid input"
    exit 1
endif

If I pipe echo to egrep it works, but it also prints the variable on the screen, and this is something I don't need.

A: 

you can use awk

$ echo "1234" | awk '{print $1+0==$1?"ok":"not ok"}'
ok
$ echo "123d4" | awk '{print $1+0==$1?"ok":"not ok"}'
not ok
ghostdog74
Thanks but I would prefer the egrep, only because I don't know awk. I will probably give it ago in the future, but as for now I don't have time to learn it.
Mike55
+2  A: 

To simply suppress output you can redirect it to the null device.

echo $1 | egrep '^[0-9]+$' >/dev/null
if ($status == 0) then
set numvar = $1
else
    echo "Invalid input"
    exit 1
endif

You might also want to consider using the -c option to get the count of matches instead of using using the status.

Also, unless you are using csh, the status is stored in $? not in $status

Michael Dillon
I used the -c option as you suggested, and I also set new variable to be used in if statement. set temp = `echo $1 | egrep -c '^[0-9]+$'` if ($temp != 0) then
Mike55
In csh, the exit status is indeed stored in `$status`
Dennis Williamson
I added a clarification about csh and will add a csh tag as well.
Michael Dillon
+2  A: 

grep has a -q option that suppresses output

So:

egrep -q '^[0-9]+$'
Peter van der Heijden
The man page says: "Portable shell scripts should avoid both -q and -s and should redirect standard and error output to /dev/null instead. (-s is specified by POSIX.)"
Dennis Williamson
@Dennis - You are right about the portability issue. Actually both the -s and -q options are specified by POSIX. The -q option acts in the way I use it here, the -s option suppresses error messages. See http://www.gnu.org/software/grep/manual/html_node/General-Output-Control.html#General-Output-Control
Peter van der Heijden
portable shell scripts probably won't be written in csh
glenn jackman