我曾经删除过一个文件或文件中的一些代码。我可以在内容(而不是提交消息)中进行grep吗?
一个非常糟糕的解决方案是grep日志:
git log -p | grep <pattern>
然而,这不会立即返回提交哈希。我和吉特·格里普玩得不亦乐乎。
我曾经删除过一个文件或文件中的一些代码。我可以在内容(而不是提交消息)中进行grep吗?
一个非常糟糕的解决方案是grep日志:
git log -p | grep <pattern>
然而,这不会立即返回提交哈希。我和吉特·格里普玩得不亦乐乎。
当前回答
git rev-list --all | xargs -n 5 git grep EXPRESSION
是对Jeet解决方案的一个调整,因此它在搜索时显示结果,而不仅仅是在最后(在大型存储库中可能需要很长时间)。
其他回答
所以,您是否正在尝试翻看旧版本的代码,以查看最后存在的内容?
如果我这样做的话,我可能会使用git平分。使用平分线,您可以指定已知的好版本、已知的坏版本,以及一个简单的脚本,该脚本可以检查版本是好还是坏(在本例中,一个grep可以查看您正在查找的代码是否存在)。运行此命令将发现代码何时被删除。
我最喜欢的方法是使用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显示。
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很有用,因为它只接受文件名,而不接受相对/系统绝对路径。
在这里查看我的完整答案以了解更多解释。
在git历史记录中搜索的命令
git log -S"alter" --author="authorname" --since=2021.1.1 --until=2023.1.1 -- .
灵感来自答案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