如何在Git历史记录中grep(搜索)已提交的代码

我过去某个时候已经删除了文件或文件中的某些代码。 我可以在内容中(而不是在提交消息中)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
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值