我曾经删除过一个文件或文件中的一些代码。我可以在内容(而不是提交消息)中进行grep吗?
一个非常糟糕的解决方案是grep日志:
git log -p | grep <pattern>
然而,这不会立即返回提交哈希。我和吉特·格里普玩得不亦乐乎。
我曾经删除过一个文件或文件中的一些代码。我可以在内容(而不是提交消息)中进行grep吗?
一个非常糟糕的解决方案是grep日志:
git log -p | grep <pattern>
然而,这不会立即返回提交哈希。我和吉特·格里普玩得不亦乐乎。
当前回答
为了简单起见,我建议使用GUI:gitk——Git存储库浏览器。它很灵活
要搜索代码:要搜索文件,请执行以下操作:当然,它还支持正则表达式:
您可以使用向上/向下箭头浏览结果。
其他回答
我接受了Jeet的答案,并将其改编为Windows(多亏了这个答案):
FOR /F %x IN ('"git rev-list --all"') DO @git grep <regex> %x > out.txt
注意,对于我来说,出于某种原因,删除这个正则表达式的实际提交并没有出现在命令的输出中,而是出现在它之前的一次提交。
在任何版本、任何文件(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
灵感来自答案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
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很有用,因为它只接受文件名,而不接受相对/系统绝对路径。
在这里查看我的完整答案以了解更多解释。