How to exclude certain directories/files from git grep search

Is there a way to search git repository using git grep but exclude certain paths/directories/files from the search? Like the --exclude option in normal grep command.

If you are curious: I don't want to use normal grep since it is much slower than git grep when the size of the git repository is large.


It's not possible, but has been discussed recently. Proposed workaround in link:

You can put *.dll to .gitignore file then git grep --exclude-standard .

EDIT see onlynone answer, since git 1.9.0 it's possible.


In git 1.9.0 the "magic word" exclude was added to pathspec s. So if you want to search for foobar in every file except for those matching *.java you can do:

git grep foobar -- './*' ':(exclude)*.java'

Or using the ! "short form" for exclude:

git grep foobar -- './*' ':!*.java'

Note that when using an exclude pathspec , you must have at least one "inclusive" pathspec . In the above examples this is the ./* (recursively include everything under the current directory).

You could also use something like :(top) (short form: :/ ) to include everything from the top of the repo. But then you'd probably also want to adjust your exclude pathspec to start from the top as well: :/!*.java (otherwise it would only exclude *.java files from under your current directory).

There's a good reference for all the "magic words" allowed in a pathspec at git-scm.com (or just git help glossary ). For some reason, the docs at kernel.org are really out of date even though they often come up first in google searches.


Update: For git >= 1.9 there is native support for exclude patterns, see onlyone's answer.

This may seem backwards, but you can pass a list of files not matching your exclude pattern to git grep like this:

git grep <pattern> -- `git ls-files | grep -v <exclude-pattern>`

grep -v returns every path not matching <exclude-pattern> . Note that git ls-files also takes a --exclude parameter, but that is only applied to untracked files.

链接地址: http://www.djcxy.com/p/8294.html

上一篇: grep不显示路径/文件:行

下一篇: 如何从git grep搜索中排除某些目录/文件