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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Find a digit

Status
Not open for further replies.

scriptfinder

Technical User
Apr 17, 2006
18
US
Hi!

I am looking to find a digit in a word.

For ex:

TEXT="Number3"

I need to find digit 3 (can be any digit 'n') in the variable $TEXT.

Can anyone please help?

Thanks.
 
A couple of ideas:

[tt]TEXT="Number3"

# Strip out any non numeric characters using sed
DIGIT=`echo $TEXT | sed 's/[^0-9]//g'`

# The same using tr
DIGIT=`echo $TEXT | tr -dc '[0-9]'`

# If it's always the last character
LENGTH=`expr length "$TEXT"`
DIGIT=`expr substr $TEXT $LENGTH 1`

# or
DIGIT=`echo $TEXT | cut -c ${LENGTH}-`[/tt]

There's probably a neat way using expr match but I don't use that much, it seems only to return whether or not there is a match, not its location in the string.

Annihilannic.
 
The Korn shell has a pattern match operator, "@(pattern)"...
Code:
TEXT=one2three

[[ ${TEXT} = @(*[0-9]*) ]] && print "TEXT has a numeric digit in it"
 
I was presuming he actually wanted to pull the digit out of it.

A ksh solution, again presuming the digit is on the end:

[tt]DIGIT=${TEXT##*[!0-9]}[/tt]

Annihilannic.
 
in any shell:

echo $TEXT | fold -w1 | grep '^[0-9]$' | head -1



HTH,

p5wizard
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top