1748154 Members
3632 Online
108758 Solutions
New Discussion юеВ

Numeric validation

 
SOLVED
Go to solution
bhoang
Advisor

Numeric validation

Is there an existing shell script out there to check for a 3 digit field to be numeric?
TIA.
6 REPLIES 6
James R. Ferguson
Acclaimed Contributor
Solution

Re: Numeric validation

Hi:

This is one method:

#!/usr/bin/sh
typeset X=$1
if [ `expr "$X" : '[0-9,\-]*'` -ne `expr "$X" : '.*'` ]
then
echo "not a number!"
else
echo "ok, is a number!"
fi
#.end.

Regards!

...JRF...
Steven Sim Kok Leong
Honored Contributor

Re: Numeric validation

Hi,

Here is another method:

#/sbin/sh
expr `echo $1|awk -F\. '{print $1$2}'` + 0
if [ "$?" != 0 ]
then
echo is NOT a number
else
echo is a number
fi

Hope this helps. Regards.

Steven Sim Kok Leong
Wodisch
Honored Contributor

Re: Numeric validation

Hello,

this one is faster since no additional processes are started:

case "$1" in
[0-9][0-9][0-9]) echo "3digit numeric" ;;
*) echo "NOT 3digit numeric" ;;
esac

HTH,
Wodisch
Steven Sim Kok Leong
Honored Contributor

Re: Numeric validation

Hi,

I agree with Wodisch, if only plain 3-digit places are required. If you want to also take care of decimal places and negatives, JRF's script takes care of them and any number of digits. Mine too.

Hope this helps. Regards.

Steven Sim Kok Leong
Peter Kloetgen
Esteemed Contributor

Re: Numeric validation

Hi,

there is a possibility which is even faster:

if (($1+1)) >/dev/null 2>&1
then
echo "$1 is a number!"
else
echo "$1 is something else
fi


Allways stay on the bright side of life!

Peter
I'm learning here as well as helping
Robin Wakefield
Honored Contributor

Re: Numeric validation

...and another way, n is the number of digits to look for:

# a=123
# n=3
echo $a | grep -E "^[0-9]{$n}$"
123
# n=4
# echo $a | grep -E "^[0-9]{$n}$"
#


Rgds, Robin.