For Programmers: Free Programming Magazines  


Home > Archive > AWK > June 2004 > How to count the occurence of a character in a word









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author How to count the occurence of a character in a word
M.H

2004-06-25, 7:20 pm

Hi,

Say that we have a word A='ddsC;dd;ee;Xv;oui'

I'd like to know if there is a method of how to count the number of
occurences of the comma (;) in the word A.

In this example : the number is 4.

Thanks.

Chris F.A. Johnson

2004-06-25, 7:20 pm

On 2004-06-25, M.H wrote:
> Hi,
>
> Say that we have a word A='ddsC;dd;ee;Xv;oui'
>
> I'd like to know if there is a method of how to count the number of
> occurences of the comma (;) in the word A.


That's a semi-colon, not a comma.

> In this example : the number is 4.


In any Bourne-type shell:

A='ddsC;dd;ee;Xv;oui'
IFS=';'
set -- x${A}x
shift
echo $#


With awk:

echo "x${A}x" | awk 'BEGIN {FS = ";"} {print NF - 1}'


With bash2 or ksh93:

A=${A//[!;]}
echo ${#A}


--
Chris F.A. Johnson http://cfaj.freeshell.org/shell
========================================
===========================
My code (if any) in this post is copyright 2004, Chris F.A. Johnson
and may be copied under the terms of the GNU General Public License
Doug McClure

2004-06-25, 7:20 pm

{
temp = A
count = gsub(/;/, "", temp)
print count
}

DKM

On Fri, 25 Jun 2004 18:47:43 +0200, "M.H" <haed98@excite.com> wrote:

>Hi,
>
>Say that we have a word A='ddsC;dd;ee;Xv;oui'
>
>I'd like to know if there is a method of how to count the number of
>occurences of the comma (;) in the word A.
>
>In this example : the number is 4.
>
>Thanks.



To contact me directly, send EMAIL to (single letters all)
DEE_KAY_EMM AT EarthLink.net. [For example X_X_X@EarthLink.net.]
Stefan Lagotzki

2004-06-25, 7:20 pm

M.H <haed98@excite.com>:
> Say that we have a word A='ddsC;dd;ee;Xv;oui'
>
> I'd like to know if there is a method of how to count the number of
> occurences of the comma (;) in the word A.


stefan2@platon:~/test> echo "ddsC;dd;ee;Xv;oui" |
awk -F';' '{print NF-1}'
4

Stefan

..
Bill Marcum

2004-06-26, 3:55 pm

["Followup-To:" header set to comp.unix.shell.]
On 25 Jun 2004 17:08:17 GMT, Chris F.A. Johnson
<cfajohnson@gmail.com> wrote:
>
> With awk:
>
> echo "x${A}x" | awk 'BEGIN {FS = ";"} {print NF - 1}'
>

Another way to do it in awk:
echo "$A" |awk '{print gsub(/;/,"",$0)}'


--
The truth you speak has no past and no future. It is, and that's all it
needs to be.
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com