Xref: utzoo comp.unix.questions:25749 comp.unix.shell:301 Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!ucsd!ucbvax!van-bc!mplex!grassys!ror From: ror@grassys.bc.ca (Richard O'Rourke) Newsgroups: comp.unix.questions,comp.unix.shell Subject: Re: Counting characters with unix utilities Summary: Text only file hint Message-ID: <163@grassys.bc.ca> Date: 25 Sep 90 03:44:43 GMT References: <4002@umbc3.UMBC.EDU> Organization: Grass Root Systems, Burnaby, B.C., Canada Lines: 47 In article <4002@umbc3.UMBC.EDU>, rouben@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@umbc.bitnet > Baltimore, MD 21228, U.S.A. rostamian@umbc3.umbc.edu Richard O'Rourke: (604)438-8249 | Grass Root Systems: 436-1995 UUCP: uunet!van-bc!mplex!grassys!ror | Smart UUCP: ror@grassys.bc.ca ror@grassys.wimsey.bc.ca |