Count occurrences of a char in plain text file

LinuxCountTerminalCharacter

Linux Problem Overview


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

Linux Solutions


Solution 1 - Linux

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.

Solution 2 - Linux

even faster:

tr -cd f < file | wc -c

Time for this command with a file with 4.9 MB and 1100000 occurences of the searched character:

real   0m0.089s
user   0m0.057s
sys    0m0.027s

Time for Vereb answer with echo, cat, tr and bc for the same file:

real   0m0.168s
user   0m0.059s
sys    0m0.115s

Time for Rob Hruska answer with tr, sed and wc for the same file:

real   0m0.465s
user   0m0.411s
sys    0m0.080s

Time for Jefromi answer with fgrep and wc for the same file:

real   0m0.522s
user   0m0.477s
sys    0m0.023s 

Solution 3 - Linux

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

where the A is the character

Time for this command with a file with 4.9 MB and 1100000 occurences of the searched character:

real   0m0.168s
user   0m0.059s
sys    0m0.115s

Solution 4 - Linux

If all you need to do is count the number of lines containing your character, this will work:

grep -c 'f' myfile

However, it counts multiple occurrences of 'f' on the same line as a single match.

Solution 5 - Linux

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncupakobView Question on Stackoverflow
Solution 1 - LinuxCascabelView Answer on Stackoverflow
Solution 2 - Linuxuser1985553View Answer on Stackoverflow
Solution 3 - LinuxVerebView Answer on Stackoverflow
Solution 4 - LinuxJongo the GibbonView Answer on Stackoverflow
Solution 5 - LinuxRob HruskaView Answer on Stackoverflow