How to exclude certain directories/files from git grep search

前端 未结 5 606
予麋鹿
予麋鹿 2020-12-12 12:59

Is there a way to exclude certain paths/directories/files when searching a git repository using git grep? Something similar to the --exclude option

5条回答
  •  不思量自难忘°
    2020-12-12 13:32

    In git 1.9.0 the "magic word" exclude was added to pathspecs. 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 in git versions up to v2.12, 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). In git v2.13 this restriction was lifted and git grep foobar -- ':!*.java' works without the ./*.

    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.

提交回复
热议问题