Simpler Navigation for Servers and Operating Systems
Completed: a much simpler Servers and Operating Systems section of the Community. We combined many of the older boards, so you won't have to click through so many levels to get at the information you need. Check the consolidated boards here as many sub-forums are now single boards.
Languages and Scripting
cancel
Showing results for 
Search instead for 
Did you mean: 

Count the occurance of a charactor in a string

SOLVED
Go to solution
Smucker
Regular Advisor

Count the occurance of a charactor in a string

I need a code snippet to determine the number of numeric digits within a string.

Ex
str="jdydh7hdyd5"

cnt=`some_function $str`

echo $cnt

any ideas
3 REPLIES
Highlighted
Biswajit Tripathy
Honored Contributor

Re: Count the occurance of a charactor in a string

some_function ()
{
integer cnt=0
str1=$1
str2=`echo $str1 | sed 's/[0-9]//g'`
cnt=${#str1}-${#str2}
echo $cnt
}

str="jdydh7hdyd5"
some_function $str


Should print 2 as there are only 2 numeric digits in
the string str.

- Biswajit
:-)
Peter Godron
Honored Contributor
Solution

Re: Count the occurance of a charactor in a string

Smucker,
how about:

cnt=`echo $str | tr -cd "[0-9]" |wc -c`

this deletes all characters beside 0-9 and then counts the characters left

Shortest answer I could find at the moment.
Hope this solves your problem.

Regards
Smucker
Regular Advisor

Re: Count the occurance of a charactor in a string

Thanks that did the trick