40

I have a piece of code in another than my current branch in my git repo, and I am not sure which commit and which branch. How can I search in all files that I committed until now for a specific string (and afterwards show the surrounding of that line of code)?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Yo Ludke
  • 2,149
  • 2
  • 23
  • 38

4 Answers4

47

Use git grep to locate the commit:

git grep "string" $(git rev-list --all)

The git rev-list --all makes it search the entire history of the project.

That will give an output like this:

<commit>:<path>:<matched line>

Then you can use git branch --contains to find out which branch the commit is on:

git branch --contains <commit>
John Szakmeister
  • 44,691
  • 9
  • 89
  • 79
  • Can I specify to search in only one file/path? (E.g. I am searching for a specific fixture and only want to search in this path) – Yo Ludke Dec 14 '12 at 12:58
  • 1
    Yes: `git grep "string" $(git rev-list --all) -- path`. – John Szakmeister Dec 14 '12 at 15:04
  • 14
    this doesn't work for big histories :( `git grep 'abc' echo $(git rev-list --all)` `zsh: argument list too long: git` – tback Jan 21 '14 at 15:35
  • 3
    If you get `Argument list too long`, you can use `git rev-list --all | xargs git grep 'abc'`: https://stackoverflow.com/a/49243541/9636 – Heath Borders Mar 12 '18 at 20:02
10

If the git grep "string" variation above is giving you "list too long" errors, you can use git log -S instead. The -S option searches the contents of the files that were committed:

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

(More in the "Pro Git" book under "searching".)

alpha_989
  • 4,882
  • 2
  • 37
  • 48
medmunds
  • 5,950
  • 3
  • 28
  • 51
4

If jszakmeister's answer gives you an Argument list too long response:

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

You can pipe it into xargs instead:

$ git rev-list --all | xargs git grep "string"
Heath Borders
  • 30,998
  • 16
  • 147
  • 256
0

change the branch with git branch "branch-name" and then do git grep "specific string" in your repository root. if you don't have too many branches this should get you there quick enough.

Alexander Oh
  • 24,223
  • 14
  • 73
  • 76