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?
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?
try it with
grep [PATTERN] -o [FILE] | wc -l
and please do not use cat if not needed.
Alternative to grep:
sed 's/[^x]//g' filename | tr -d '\012' | wc -c
where x
is the character you want to count.
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).
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.