gitgrepgit-grep

File names only using 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?


Solution

  • 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.