views:

651

answers:

5

I have a few text files and I'd like to count how many times a letter appears in each?

Specifically, I'd like to use the UNIX shell to do this, in the form of: cat file | .... do stuff...

Is there a way I can get the wc command to do this?

+5  A: 
grep char -o filename | wc -l
SilentGhost
Won't this just count one occurrence per line. So if the char appears twice it will only be counted once.
Brian Gianforcaro
why don't you try and see? `grep -o` outputs each occurrence on its own line.
SilentGhost
Brian, it will work. just tested it.
Aviator
My apologizes, It did work quite well.
Brian Gianforcaro
A: 

try it with

grep  [PATTERN] -o [FILE] | wc -l

and please do not use cat if not needed.

BeowulfOF
What's so wrong with using cat?
samoz
it doesn't count multiple characters per line
SilentGhost
@samoz:cat is wrong, since it should input the read file to another program - the other program is able to read the file by itself, so the use of cat is unneeded and complicates the codeline. @SilentGhost: your right.
BeowulfOF
+1  A: 

Alternative to grep:

sed 's/[^x]//g' filename | tr -d '\012' | wc -c

where x is the character you want to count.

hlovdal
A: 

There's also awk:

$ echo -e "hello world\nbye all" | awk -Fl '{c += NF - 1} END {print c}'
5

Change -Fl to -F<your character>.

This works by setting the field delimiter to the character specified by -F, then accumulating the number of fields on each line - 1 (because if there's one delimiter, there are two fields - but we should only count 1).

Mark Rushakoff
+1  A: 

Another alternative:

tr -d -C X <infile | wc -c

where X is the character or string of characters you want to count and infile is the input file.

Scott Lindsay