Operating System - HP-UX
1753517 Members
5097 Online
108795 Solutions
New Discussion юеВ

count the repeating charcter in a word

 
SOLVED
Go to solution
Kris_5
Occasional Advisor

count the repeating charcter in a word

Hi,

I am trying to count the number of times a particular charcter repeated in a word. Could any one help me with a single line command for this problem. TIA

Kris
5 REPLIES 5
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: count the repeating charcter in a word

Here is one rather silly approach:

TARG="s"
echo "Class" | awk -v targ="${TARG}" '{print gsub(targ,"FurpSplat")}'

In this case, we are looking for how many times
's' appears in "Class". gsub returns the number of substitutions made so that we print '2'.
If it ain't broke, I can fix that.
harry d brown jr
Honored Contributor

Re: count the repeating charcter in a word


Here's a good site for many different solutions (although it's word counting):

http://www.bagley.org/~doug/shootout/bench/wordfreq/

live free or die
harry

Live Free or Die
Steven Sim Kok Leong
Honored Contributor

Re: count the repeating charcter in a word

Hi,

Here's another shell-silly way:

# WORD=root
# PATTERN=o
# i=1 ; while [ "$i" -lt "`echo $WORD | wc -c`" ] ; do echo $WORD | cut -c$i ; i=`expr $i + 1` ; done | grep $PATTERN | wc -l

Hope this helps. Regards.

Steven Sim Kok Leong
Steven Sim Kok Leong
Honored Contributor

Re: count the repeating charcter in a word

Hi,

Okay, you said everything on a single line :P

# WORD=root ; PATTERN=o ; i=1 ; while [ "$i" -lt "`echo $WORD | wc -c`" ] ; do echo $WORD | cut -c$i ; i=`expr $i + 1` ; done | grep $PATTERN | wc -l
2

Hope this helps. Regards.

Steven Sim Kok Leong
H.Merijn Brand (procura
Honored Contributor

Re: count the repeating charcter in a word

Count 'i' in 'Particularity'

# perl -le '$word="Particularity";print$word=~y/i//d'
2
Enjoy, Have FUN! H.Merijn