我曾经删除过一个文件或文件中的一些代码。我可以在内容(而不是提交消息)中进行grep吗?

一个非常糟糕的解决方案是grep日志:

git log -p | grep <pattern>

然而,这不会立即返回提交哈希。我和吉特·格里普玩得不亦乐乎。


当前回答

git rev-list --all | xargs -n 5 git grep EXPRESSION

是对Jeet解决方案的一个调整,因此它在搜索时显示结果,而不仅仅是在最后(在大型存储库中可能需要很长时间)。

其他回答

我最喜欢的方法是使用gitlog的-G选项(在1.7.4版本中添加)。

-G<regex>
       Look for differences whose added or removed line matches the given <regex>.

-G和-S选项确定提交是否匹配的方式存在细微差异:

-S选项本质上统计提交前后搜索在文件中匹配的次数。如果前后计数不同,则提交将显示在日志中。例如,这不会显示移动了与搜索匹配的行的提交。使用-G选项,如果您的搜索与添加、删除或更改的任何行相匹配,则提交将显示在日志中。

以此次提交为例:

diff --git a/test b/test
index dddc242..60a8ba6 100644
--- a/test
+++ b/test
@@ -1 +1 @@
-hello hello
+hello goodbye hello

因为在提交之前和之后“hello”在文件中出现的次数相同,所以使用-Shello将不匹配。然而,由于对匹配hello的行进行了更改,提交将使用-Gello显示。

我在这里有点惊讶,也许我错过了我正在寻找的答案,但我来到这里是为了寻找所有树枝的顶端。并不是针对存储库中的每一个修订,所以对我来说,使用git-rev列表——所有信息都太多了。

换句话说,对我来说,最有用的变化是

git grep -i searchString $(git branch -r)

or

git branch -r | xargs git grep -i searchString

or

git branch -r | xargs -n1 -i{} git grep -i searchString {}

当然,您可以在这里尝试正则表达式方法。这里的方法很酷的是,它直接针对远程分支。我不必在这些分支机构中的任何一家进行检查。

灵感来自答案https://stackoverflow.com/a/2929502/6041515,我发现gitgrep似乎在每次提交时都会搜索完整的代码库,而不仅仅是差异,结果往往重复且冗长。下面的脚本将只搜索每个git提交的差异:

for commit in $(git rev-list --all); do 
    # search only lines starting with + or -
    if  git show "$commit" | grep "^[+|-].*search-string"; then 
        git show --no-patch --pretty=format:'%C(yellow)%h %Cred%ad %Cblue%an%Cgreen%d %Creset%s' --date=short $commit
    fi  
done

示例输出,底部的gitcommit是第一次引入我正在搜索的更改的gitcommit:

csshx$ for commit in $(git rev-list --all); do 
>     if  git show "$commit" | grep "^[+|-].*As csshX is a command line tool"; then 
>         git show --no-patch --pretty=format:'%C(yellow)%h %Cred%ad %Cblue%an%Cgreen%d %Creset%s' --date=short $commit
>     fi  
> done

+As csshX is a command line tool, no special installation is needed. It may
987eb89 2009-03-04 Gavin Brock Added code from initial release

gitlog可以是搜索所有分支中文本的更有效的方法,特别是如果有很多匹配项,并且您希望首先看到最近的(相关的)更改。

git log -p --all -S 'search string'
git log -p --all -G 'match regular expression'

这些日志命令列出了添加或删除给定搜索字符串/regex的提交,(通常)是最新的。-p选项会导致相关的diff显示在添加或删除模式的位置,因此您可以在上下文中看到它。

找到了添加您要查找的文本的相关提交(例如,8beeff00d)后,找到包含该提交的分支:

git branch -a --contains 8beeff00d

在任何版本、任何文件(Unix/Linux)中搜索:

git rev-list --all | xargs git grep <regexp>

仅在某些给定文件中搜索,例如XML文件:

git rev-list --all | xargs -I{} git grep <regexp> {} -- "*.xml"

结果行应如下所示:6988bec26b1503d45eb0b2e8a4364afb87dde7af:bla.xml:找到的行的文本。。。

然后,您可以使用gitshow获取更多信息,如作者、日期和差异:

git show 6988bec26b1503d45eb0b2e8a4364afb87dde7af