Mike55
Mike55

Reputation: 497

How to egrep variable-Unix shell script

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.

Upvotes: 1

Views: 8604

Answers (3)

Michael Dillon
Michael Dillon

Reputation: 32392

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

Upvotes: 4

heijp06
heijp06

Reputation: 11808

grep has a -q option that suppresses output

So:

egrep -q '^[0-9]+$'

Upvotes: 3

ghostdog74
ghostdog74

Reputation: 342739

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

Upvotes: 0

Related Questions