我过去某个时候已经删除了文件或文件中的某些代码。 我可以在内容中(而不是在提交消息中)grep吗?
一个非常糟糕的解决方案是grep日志:
git log -p | grep <pattern>
但是,这不会立即返回提交哈希。 我和git grep
玩了无济于事。
#1楼
我最喜欢的方法是使用git log
的-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
的行进行了更改,因此将使用-Ghello
显示提交。
#2楼
如果您想浏览代码更改(请查看整个历史记录中给定单词实际更改的内容),请使用patch
模式-我发现这样做非常有用:
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 ;) )
#3楼
@Jeet的答案在PowerShell中有效。
git grep -n <regex> $(git rev-list --all)
以下显示所有提交中包含password
所有文件。
# store intermediate result
$result = git grep -n "password" $(git rev-list --all)
# display unique file names
$result | sel