haz
September 10, 2006, 6:36am
1
G'day guys, first post so be gentle.
I need help with some code to work out if a variable (string) contains any integers. The valid variable (string) must contain only letters.
Also need to be able to work out if a variable contains only integers.
Any help greatly appreciated.
vino
September 10, 2006, 7:31am
2
Welcome to the forums. We have a search feature which you can use to see if similiar problems have encountered before.
See - ksh : find value type
you can try this?
if ! [ $var -ge 0 -o $var -lt 0 ]; then
echo "string"
....
haz
September 10, 2006, 8:03am
4
Sorry, should have specified it is a Bourne shell script that I am writing.
This is what I've tried writing, where am i going wrong?
namenum=$1
if [ "$namenum" -eq *[a-zA-Z]* ] ; then
echo "$namenum is all alphabetic"
else
echo "not all alphabetic"
fi
Try:
#! /bin/sh
namenum=$1
echo $namenum | grep [0-9] > /dev/null
if [ $? -eq 0 ] ; then
echo "non-alpha"
else
echo "alpha"
fi
haz
September 10, 2006, 8:43am
6
Thanks, that did it perfectly. I changed it so it would check the other way round using -ne instead of -eq.
Andrek
September 11, 2006, 2:45am
7
try "tr"
Do a man on tr
basiclly
# echo "AbCd67Fg8" | tr -d "[:alpha:]"
# 678
So test for null variables
ie
#!/bin/sh
var=AbCd67g8
if [ -z `echo $var | tr -d "[:alpha:]"` ]
then
echo "ONLY Alpha chars here!" # You had only A-z
else
echo "Sorry you have other stuff" # You have soming else besides A-z?
fi
True, this is a most comprehensive approach.