127

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.

Vinay
  • 6,204
  • 6
  • 38
  • 55

3 Answers3

201

Yes, for example:

git grep res -- '*.js'
CB Bailey
  • 755,051
  • 104
  • 632
  • 656
  • 5
    One slight modification - if you're not in the root of your repository, `git grep res -- '/*.js'` might be better... – twalberg Dec 13 '12 at 21:18
  • 1
    @twalberg: But the comment suggests that he wants to look from the current directory [down], surely? – CB Bailey Dec 13 '12 at 21:20
  • Ah... right... The question didn't specifically say that, but the comment in the code block does. – twalberg Dec 13 '12 at 21:21
  • I do wish to search from the current directory down. – Vinay Dec 13 '12 at 22:59
  • Just saw your comment @twalberg. That's exactly what I needed for searching from a given path. :-) – Vinay Dec 13 '12 at 23:39
  • @Vinay: The simplest way is to `cd` to where you wan to search from and run `git grep` from there. This is the common use case that `git grep` was designed for. – CB Bailey Dec 14 '12 at 06:53
  • 7
    Just extra information: If you wish to specify a set of file extensions you can use `git grep res -- *.js *.cs` this is covered in another [question](http://stackoverflow.com/questions/21599474/how-to-git-grep-only-a-set-of-file-extentions) – stk_sfr Feb 06 '14 at 10:03
  • 4
    what does the `--` accomplish? – aehlke Apr 12 '16 at 17:43
  • 2
    An important thing to not forget is the single quotes around '*.js'. If they are not there, it will not work. (the shell will intercept it before it reaches git). – hasen Sep 20 '17 at 05:09
  • git grep res -- '*.proto' gave me what I needed. Thanks. – Down the Stream Oct 11 '18 at 21:17
  • 4
    aehlke `--` is a common delimiter in many of git's commands to separate arguments with a set of files to operate on. – Moberg Apr 24 '20 at 10:32
2

Try doing this :

find . -type f -iname '*.js' -exec grep -i 'pattern' {} +
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
0

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

Kay V
  • 3,738
  • 2
  • 20
  • 20