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

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

git log -p | grep <pattern>

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


当前回答

所以,您是否正在尝试翻看旧版本的代码,以查看最后存在的内容?

如果我这样做的话,我可能会使用git平分。使用平分线,您可以指定已知的好版本、已知的坏版本,以及一个简单的脚本,该脚本可以检查版本是好还是坏(在本例中,一个grep可以查看您正在查找的代码是否存在)。运行此命令将发现代码何时被删除。

其他回答

如果您想浏览代码更改(查看整个历史中给定单词的实际更改),请选择补丁模式-我发现了一个非常有用的组合:

git log -p
# Hit '/' for search mode.
# Type in the word you are searching.
# If the first search is not relevant, hit 'n' for next (like in Vim ;) )

A.完整、唯一、排序的路径:

# Get all unique filepaths of files matching 'password'
# Source: https://stackoverflow.com/a/69714869/10830091
git rev-list --all | (
    while read revision; do
        git grep -F --files-with-matches 'password' $revision | cat | sed "s/[^:]*://"
    done
) | sort | uniq

B.唯一、排序的文件名(不是路径):

# Get all unique filenames matching 'password'
# Source: https://stackoverflow.com/a/69714869/10830091
git rev-list --all | (
    while read revision; do
        git grep -F --files-with-matches 'password' $revision | cat | sed "s/[^:]*://"
    done
) | xargs basename | sort | uniq

第二个命令对BFG很有用,因为它只接受文件名,而不接受相对/系统绝对路径。

在这里查看我的完整答案以了解更多解释。

Jeet的答案在PowerShell中有效。

git grep -n <regex> $(git rev-list --all)

下面显示了任何提交中包含密码的所有文件。

# Store intermediate result
$result = git grep -n "password" $(git rev-list --all)

# Display unique file names
$result | select -unique { $_ -replace "(^.*?:)|(:.*)", "" }

为了简单起见,我建议使用GUI:gitk——Git存储库浏览器。它很灵活

要搜索代码:要搜索文件,请执行以下操作:当然,它还支持正则表达式:

您可以使用向上/向下箭头浏览结果。

我最喜欢的方法是使用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显示。