Counting characters with unix utilities

rouben at math9.math.umbc.edu rouben at math9.math.umbc.edu
Mon Sep 24 06:34:26 AEST 1990


How can I count the number of occurrences of a given character in a file?
It can be done rather trivially in C, but I wonder if it can also be done
using standard unix utilities like awk, sed, tr, wc, etc.

The closest  I have come to this is the following construction:

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 feel that I am missing something, and that there should be an easy way
to count characters a la unix.  Any hints?

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

--
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



More information about the Comp.unix.shell mailing list