Counting characters with unix utilities

Edward Vielmetti emv at math.lsa.umich.edu
Mon Sep 24 08:16:58 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?
   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

This is what I came up with in perl, after about 15 minutes of digging
in the perl info pages:

   cat file | perl -ne '$c += tr/A/A/; if (eof()) {print "$c\n";}'

Going back to the tr man page this one seems to work too:

   cat file | tr -cd 'A' | wc -c

I don't see an easy perl equivalent of the "tr -cd" idiom.

--Ed

Edward Vielmetti, U of Michigan math dept <emv at math.lsa.umich.edu>
moderator, comp.archives



More information about the Comp.unix.shell mailing list