How to exclude certain directories/files from git grep search
有没有一种方法可以使用
如果您好奇的话:我不想使用普通grep,因为当git存储库的大小很大时,它比
在git 1.9.0中,在
1 | git grep foobar -- './*' ':(exclude)*.java' |
或使用
1 | git grep foobar -- './*' ':!*.java' |
注意,当使用exclude
您还可以使用类似于
在git-scm.com(或仅在
更新:对于git>=1.9,存在对排除模式的本机支持,请参见OnlyOne的答案。
这可能看起来是向后的,但您可以将与排除模式不匹配的文件列表传递给
1 | git grep <pattern> -- `git ls-files | grep -v <exclude-pattern>` |
这是不可能的,但最近已经讨论过了。链接中的建议解决方案:
You can put
*.dll to .gitignore file thengit grep --exclude-standard .
编辑-只查看你的答案,因为Git 1.9.0是可能的。
以@kynan的例子为基础,我编写了这个脚本,并将它作为
在我们的repo中,它有很多图像,所以我排除了图像文件,如果我搜索整个repo,这将把serchtime降到1/3。但是可以很容易地修改脚本以排除其他文件类型或geleralPatterns。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | #!/bin/bash # # Wrapper of git-grep that excludes certain filetypes. # NOTE: The filetypes to exclude is hardcoded for my specific needs. # # The basic setup of this script is from here: # https://stackoverflow.com/a/14226610/42580 # But there is issues with giving extra path information to the script # therefor I crafted the while-thing that moves path-parts to the other side # of the '--'. # Declare the filetypes to ignore here EXCLUDES="png xcf jpg jpeg pdf ps" # Rebuild the list of fileendings to a good regexp EXCLUDES=`echo $EXCLUDES | sed -e 's/ /\\\|/g' -e 's/.*/\\\.\\\(\0\\\)/'` # Store the stuff that is moved from the arguments. moved= # If git-grep returns this"fatal..." then move the last element of the # arg-list to the list of files to search. err="fatal: bad flag '--' used after filename" while ["$err" ="fatal: bad flag '--' used after filename" ]; do { err=$(git grep"$@" -- `git ls-files $moved | grep -iv"$EXCLUDES"` \ 2>&1 1>&3-) } 3>&1 # The rest of the code in this loop is here to move the last argument in # the arglist to a separate list $moved. I had issues with whitespace in # the search-string, so this is loosely based on: # http://www.linuxjournal.com/content/bash-preserving-whitespace-using-set-and-eval x=1 items= for i in"$@"; do if [ $x -lt $# ]; then items="$items "$i"" else moved="$i $moved" fi x=$(($x+1)) done eval set -- $items done # Show the error if there was any echo $err |
注释1
根据这一点,应该可以将该对象命名为
1 | $ git gg searchstring |
但我做不到。我在我的
注释2
该命令不能成为常规的
通过在存储库中创建属性文件,可以将文件或目录标记为二进制文件,例如:
1 2 3 4 | $ cat .git/info/attributes directory/to/ignore/*.* binary directory/to/ignore/*/*.* binary another_directory/to/also/ignore/*.* binary |
二进制文件中的匹配项没有包含行,例如
1 2 3 | $ git grep"bar" Binary file directory/to/ignore/filename matches other_directory/other_filename: foo << bar - bazz[:whatnot] |