Vinay
Vinay

Reputation: 6342

git grep by file extensions

I know that, if I wanted to grep for a pattern only on files with certain extensions, I could do this:

// searches recursively and matches case insensitively in only javascript files
// for "res" from the current directory
grep -iIr --include=*.js res ./

I've been trying to search for a way to do this via git grep as well (to take advantage of git grep's speed from the indexes it stores with its tree), but to no avail. I saw here that excluding certain file types is not possible.

Upvotes: 134

Views: 49027

Answers (4)

Gabriel Staples
Gabriel Staples

Reputation: 53165

Quick summary

# Search only in files ending in .h or .c
git grep 'my search' -- '*.[ch]'

Details

man git grep shows the following. Check out the description of <pathspec>, as well as the several examples here:

       <pathspec>...
           If given, limit the search to paths matching at least one pattern.
           Both leading paths match and glob(7) patterns are supported.

           For more details about the <pathspec> syntax, see the pathspec
           entry in gitglossary(7).

EXAMPLES
       git grep 'time_t' -- '*.[ch]'
           Looks for time_t in all tracked .c and .h files in the working
           directory and its subdirectories.

       git grep -e '#define' --and \( -e MAX_PATH -e PATH_MAX \)
           Looks for a line that has #define and either MAX_PATH or PATH_MAX.

       git grep --all-match -e NODE -e Unexpected
           Looks for a line that has NODE or Unexpected in files that have
           lines that match both.

       git grep solution -- :^Documentation
           Looks for solution, excluding files in Documentation.

Two really good examples above are:

# Looks for time_t in all tracked .c and .h files in the working
# directory and its subdirectories.
git grep 'time_t' -- '*.[ch]'

# Looks for solution, excluding files in Documentation.
git grep solution -- :^Documentation

Notice the glob *.[ch] pattern in the first one to mean "anything.h or anything.c", and the :^ in the second one to mean "not". So, apparently :^Documentation means "not in the Documentation file or folder".

Going further

  1. My answer: All about searching (via grep or similar) in your git repositories

Upvotes: 1

Kay V
Kay V

Reputation: 4046

if you want to search across all branches, you can use the following:

git log -Sres --all --name-only -- '*.js'

(I see you specify git grep; to me the approach here seems simpler and easier to remember--more like other operations I need commonly.)

Upvotes: 0

CB Bailey
CB Bailey

Reputation: 793099

Yes, for example:

git grep res -- '*.js'

Upvotes: 212

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185760

Try doing this :

find . -type f -iname '*.js' -exec grep -i 'pattern' {} +

Upvotes: 1

Related Questions