Counting all occurrences of a string within all files in a folder
You're close. To get a total count of all occurrences of "ha" within all .txt files in a folder:
grep -o "ha" *.txt | wc -l
From man grep
:
-o, --only-matching
Print only the matched (non-empty) parts of a matching line, with
each such part on a separate output line.
This works because each match is printed on a separate line, thus allowing wc -l
to count all of them.
By default, however, grep only finds the first occurrence on a line and outputs the whole line. Likewise, option -c
only finds the first occurrence in all lines, then outputs how many lines had 1 (or more) matches.
EDIT:
Here is a way to print the total number of occurrences within each individual file (with filenames):
find *.txt -printf 'echo "$(grep -o "ha" %p | wc -l) %p";' | sh
#Example output
3 file1.txt
1 file2.txt
Explanation:
find *.txt
- finds .txt files
-printf
- prints everything between the single-quotes (formatted) to standard output, replacing occurrences of %p
with find's output (file names)
$(grep -o "ha" %p | wc -l)
- works as above
| sh
- the output from -printf
(which are commands) are piped to a shell and executed
Note that printf is invoked once per filename.
Instead of using grep
, try use ag -c ha
SilverSearcher:
1.txt:3
2.txt:1
It is more faster! If you are using ubuntu, you can install package silversearcher-ag
.