Counting characters with unix utilities

Richard O'Rourke ror at grassys.bc.ca
Tue Sep 25 13:44:43 AEST 1990


In article <4002 at umbc3.UMBC.EDU>, rouben at math9.math.umbc.edu writes:
> How can I count the number of occurrences of a given character in a file?
[ stuff deleted ]
> 
> cat file | tr -c 'A' '' | wc -c
> 
> which attempts to count the number of occurrences of the character "A"
> in the file.  The "tr" command replaced all characters different from
> "A" by the null character, then "wc" counts all characterters in its input
> (unfortunately) also counting the null characters :-(

I'm not sure that what you think `tr` does in this case is what
happens in reality.  I respectfully suggest re-reading the tr man page.

> 
> I feel that I am missing something, and that there should be an easy way
> to count characters a la unix.  Any hints?

I did not test this extensively, and I'm sure that it will work only on
textual files.  Sure to be bettered and or critiqued:

#
#  Count # of 'A' chars in a file 
#  use $0 filename
#
set `sed 's/[^A]//g
     /^$/d
' $1 | sed 's/ //g' | wc`
echo $3 - $2 | bc
#
#  End of script

> 
> [If it matters, the operating system is ultrix and the shells are sh and csh.]

The above seems to work with sh.

> 
> --
> Rouben Rostamian                               Telephone: (301) 455-2458
> Department of Mathematics and Statistics       e-mail:
> University of Maryland Baltimore County        rostamian at umbc.bitnet
> Baltimore, MD 21228,  U.S.A.                   rostamian at umbc3.umbc.edu

Richard O'Rourke: (604)438-8249      | Grass Root Systems: 436-1995
UUCP: uunet!van-bc!mplex!grassys!ror | Smart UUCP: ror at grassys.bc.ca
ror at grassys.wimsey.bc.ca             |



More information about the Comp.unix.shell mailing list