Git-Repo在所有已提交文件中搜索String(未知分支和提交)

Yo *_*dke 21 git

我在我的git repo中有一段代码而不是我当前的分支,我不确定哪个提交和哪个分支.我怎样才能搜索到目前为止为特定字符串提交的所有文件(之后显示该行代码的周围)?

Joh*_*ter 25

使用git grep定位承诺:

git grep "string" $(git rev-list --all)
Run Code Online (Sandbox Code Playgroud)

git rev-list --all使得搜索项目的整个历史.

这将产生如下输出:

<commit>:<path>:<matched line>
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用git branch --contains以找出提交所在的分支:

git branch --contains <commit>
Run Code Online (Sandbox Code Playgroud)

  • 这对大历史不起作用:(`git grep'abc'echo $(git rev-list --all)``zsh:参数列表太长:git` (10认同)
  • 如果你得到`参数列表太长`,你可以使用`git rev-list --all | xargs git grep 'abc'`:/sf/answers/3447047901/ (3认同)

med*_*nds 6

如果git grep "string"上面的变体给您“列出太长”的错误,您可以git log -S改用。-S 选项搜索已提交文件的内容:

git log -S "string"  # look for string in every file of every commit
git log -S "string" -- path/to/file  # only look at the history of the named file
Run Code Online (Sandbox Code Playgroud)

(更多在“搜索”下的“Pro Git”一书中。)


Hea*_*ers 6

如果jszakmeister 的回答给了你Argument list too long回应:

$ git grep "string" $(git rev-list --all)
-bash: /usr/local/bin/git: Argument list too long
Run Code Online (Sandbox Code Playgroud)

您可以将其xargs通过管道输入:

$ git rev-list --all | xargs git grep "string"
Run Code Online (Sandbox Code Playgroud)