45

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)?

1

4 Answers 4

55

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>
Sign up to request clarification or add additional context in comments.

4 Comments

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)
Yes: git grep "string" $(git rev-list --all) -- path.
this doesn't work for big histories :( git grep 'abc' echo $(git rev-list --all) zsh: argument list too long: git
If you get Argument list too long, you can use git rev-list --all | xargs git grep 'abc': stackoverflow.com/a/49243541/9636
12

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".)

Comments

7

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"

5 Comments

How to escape this command after it is done?
What do you mean by escape this command?
Anyway to avoid xargs: git: terminated by signal 11 ?
@HeathBorders, what would be the right syntax for git grep "string" -- '*.txt'? This command alone works as expected, but with piping it returns nothing.
You'd have to research how to use xargs to inject arguments at specific places, or find out how git-grep behaves with --. I suspect your issue is that xargs expects commands to read from stdin, and maybe that doesn't happen when you use --.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.