开发者

How to egrep variable-Unix shell script

开发者 https://www.devze.com 2022-12-10 15:05 出处:网络
I’m trying to validate input by using egrep and regex.Here is the line from script (c-shell): echo $1 | egrep \'^[0-9]+$\'

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 开发者_如何学JAVAI pipe echo to egrep it works, but it also prints the variable on the screen, and this is something I don't need.


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


grep has a -q option that suppresses output

So:

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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消