grep -G '{string}' *. | wc -l Gives me the TOTAL count of the {string} in the entire directory. And on the other had wc -l *. gives me the count of each line per file but not count per file for the {string} of my interest. I am looking for something of a combination of the two, where I can count the occurrence of a {string} per file separately.
2 Answers
The grep option you need is -c:
-c
Write only a count of selected lines to standard output.
If you have nested directory in which you like to search :
find /your_dir -type f -exec grep -cF '{string}' {} +
Or if GNU Grep is avaible to you (or any other implementation of grep which supports -r) to do a recursive search:
grep -rcF '{string}' your_dir
If the directory does not hold subdirectory inside, a simple:
grep -cF '{string}' your_dir/*
will work.
Note also that -G (GNU Grep specific) enables BRE engine which is the default choices and which does not handle ERE tag like { (if not escaped). Consider to use -F options to force grep to search for simple string or to disable regex metacharcter interpolations when not needed.
-
1'grep -rcF '{string}' your_dir' was it, short and accurate, thanks!Sudoh– Sudoh2022-07-19 18:38:16 +00:00Commented Jul 19, 2022 at 18:38
grep's option -c prints a count of the selected lines per file.
grep -c '{string}' *.
(Option -G (basic regular expression) is redundant as this is the default.)
With the example files
file1
foo
bar
baz
foo
bar
file2
foo
bar
baz
foo
bar
foo
foo
bar
bar foo
baz
foo
bar
I get this result:
$ fgrep -c foo file*
file1:2
file2:6
If your file name pattern matches only one file, grep will not print the file name. To avoid this you can use option -H if you have GNU grep.
grep -cH '{string}' *.
(Adding /dev/null instead of the non-standard option -H would show the count 0 for this additional file.)