views:

512

answers:

4

Is there any way under linux/terminal to count, how many times the char f occurs in a plain text file?

+4  A: 

echo $(cat <file> | wc -c) - $(cat <file> | tr -d 'A' | wc -c) | bc

where the A is the character

Vereb
This gets about a third faster if you take out the unnecessary `cat` s, giving the filename as an argument to `wc` and `tr`.
Jefromi
unfortunately tr works only on the standard input
Vereb
If you realy want to optimize this reads the file just once: echo $(stat -c%s <file>) - $(cat <file> | tr -d 'A' | wc -c) | bc
Vereb
+1  A: 

tr -d '\n' < file | sed 's/A/A\n/g' | wc -l

Replacing the two occurrences of "A" with your character, and "file" with your input file.

  • tr -d '\n' < file: removes newlines
  • sed 's/A/A\n/g: adds a newline after every occurrence of "A"
  • wc -l: counts the number of lines

Example:

$ cat file
abcdefgabcdefgababababbbba


1234gabca

$ tr -d '\n' < file | sed 's/a/a\n/g' | wc -l
9
Rob Hruska
+7  A: 

How about this:

fgrep -o f <file> | wc -l

Note: Besides much easier to remember/duplicate and customize, this is about three times (sorry, edit! botched the first test) faster than Vereb's answer.

Jefromi
that is better than mine
Vereb
Nice answer, very simple.
Rob Hruska
Yours is pretty cool, though. I had fun reading it and seeing how it worked.
Jefromi
A: 

Although this topic is dead, I'd like to point out that

grep -c 'f' myfile

would also work

Jongo the Gibbon