按文件扩展名进行 git grep

问题描述 投票:0回答:4

我知道,如果我只想在具有特定扩展名的文件上 grep 查找模式,我可以这样做:

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

我一直在尝试寻找一种通过 git grep 来执行此操作的方法(以利用 git grep 与树一起存储的索引的速度),但无济于事。我看到here排除某些文件类型是不可能的。

git grep file-extension
4个回答
204
投票

是的,例如:

git grep res -- '*.js'

1
投票

尝试这样做:

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

0
投票

如果您想跨所有分支搜索,您可以使用以下命令:

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

(我看到你指定了 git grep;对我来说,这里的方法似乎更简单、更容易记住——更像是我通常需要的其他操作。)


0
投票

快速总结

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

详情

man git grep
显示以下内容。查看
<pathspec>
的描述,以及这里的几个示例:

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

上面两个非常好的例子是:

# 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

注意第一个中的 glob

*.[ch]
模式表示“anything.h 或 everything.c”,第二个中的
:^
表示“not”。所以,显然
:^Documentation
的意思是“不在
Documentation
文件或文件夹中”。

© www.soinside.com 2019 - 2024. All rights reserved.