Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File names only using Git grep

Tags:

git

grep

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?

like image 748
Anushi Maheshwari Avatar asked Feb 25 '18 06:02

Anushi Maheshwari


2 Answers

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.

like image 102
Sundeep Avatar answered Sep 25 '22 14:09

Sundeep


git grep --files-with-matches 'bar'

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

like image 25
Stephen Burke Avatar answered Sep 25 '22 14:09

Stephen Burke