21

I want to look only at distinct files which have a certain word in their text.

current_directory$ git grep 'word'

shows each line of the file which has a matching word.

So I tried this

current_directory$ git grep 'word' -- files-with-matches
current_directory$ git grep 'word' -- name-only

But it doesn't show any output.

Also, how can I count the total occurrences of 'word' in all files?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anushi Maheshwari
  • 439
  • 1
  • 5
  • 9
  • 3
    It’s `--files-with-matches`. No space after the `--`. – Ry- Feb 25 '18 at 06:22
  • @Ryan current_directory$ git grep 'word' --files-with-matches fatal: bad flag '--files-with-matches' used after filename – Anushi Maheshwari Feb 25 '18 at 06:27
  • 1
    Oh, you also have to put options before non-options. `git grep --files-with-matches 'word'` – Ry- Feb 25 '18 at 06:36
  • You don't need that silly long name there is a short option `grep -l 'word'` option. And if you want to opposite use `grep -L 'word'` – jcubic May 30 '23 at 18:38

2 Answers2

32

The error message helps:

$ git grep 'foo' --files-with-matches
fatal: option '--files-with-matches' must come before non-option arguments

$ git grep --files-with-matches 'foo'
<list of matching files>

To count the words, this is how I'd do it with GNU grep (I am not sure if git grep has the relevant options):

$ grep --exclude-dir=.git -RowF 'foo' | wc -l
717

From man grep:

-R, --dereference-recursive
Read all files under each directory, recursively. Follow all symbolic links, unlike -r.

-o, --only-matching
Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

-w, --word-regexp
Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character.
Word-constituent characters are letters, digits, and the underscore.

-F, --fixed-strings
Interpret PATTERN as a list of fixed strings (instead of regular expressions), separated by newlines, any of which is to be matched.

--exclude-dir=DIR
Exclude directories matching the pattern DIR from recursive searches.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sundeep
  • 23,246
  • 2
  • 28
  • 103
5
git grep --files-with-matches 'bar'

"--files-with-matches" needs to be before your search string

Stephen Burke
  • 51
  • 1
  • 1