Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

csh if ; to check if characters are not numbers

Status
Not open for further replies.

irixfan

IS-IT--Management
May 14, 2002
57
FI
In a csh script I check if a variable (one character) is not a number:
if ($myvar !~ [0-9]) then
How to do the same for say the first three characters of any variable?
I mean if any of them is not a number then...
 


Learn something new every day. I didn't know you could do that in CSH. Neat.

I would have done it the long way

echo $myvar | egrep '^[0-9][0-9]*$' >&! /dev/null
if ($status != 0 ) then
echo "Variable isn't all digits "
exit
endif

which makes the answer to your question a very simple modification

Either....

echo $myvar | cut -c1-3 | egrep '^[0-9][0-9]*$' >&! /dev/null
if ($status != 0 ) then
echo "First 3 characters of Variable aren't all digits "
exit
endif

or

echo $myvar | egrep '^[0-9][0-9][0-9]' >&! /dev/null
if ($status != 0 ) then
echo "First 3 characters of Variable aren't all digits "
exit
endif


 
Hi,
Can anyone tell me how to do the same in bash i.e. I don't want to use the echo|egrep mechanism. I want to know how to do pattern matching in bash.
Cheers,
Pravin.
 
Here is a ksh way of doing this. Adapt as needed for bash:

#! /bin/ksh
# Returns True if its argument is a valid number.
# The first pattern requires a digit before the decimal
# point, and the second after the decimal point.

function isnum
{
case $1 in
?([-+])+([0-9])?(.)*([0-9])?([Ee]?([-+])+([0-9])) )
return 0;;
?([-+])*([0-9])?(.)+([0-9])?([Ee]?([-+])+([0-9])) )
return 0;;
*) print "\nNot a number.\n" ;;
esac
}

isnum $1
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top