How to grep (search) committed code in the Git history

后端 未结 15 1213

I have deleted a file or some code in a file sometime in the past. Can I grep in the content (not in the commit messages)?

A very poor solution is to grep the log:

15条回答
  •  情深已故
    2020-11-22 06:44

    My favorite way to do it is with git log's -G option (added in version 1.7.4).

    -G
           Look for differences whose added or removed line matches the given .
    

    There is a subtle difference between the way the -G and -S options determine if a commit matches:

    • The -S option essentially counts the number of times your search matches in a file before and after a commit. The commit is shown in the log if the before and after counts are different. This will not, for example, show commits where a line matching your search was moved.
    • With the -G option, the commit is shown in the log if your search matches any line that was added, removed, or changed.

    Take this commit as an example:

    diff --git a/test b/test
    index ffffdc242..60a8ba6 100644
    --- a/test
    +++ b/test
    @@ -1 +1 @@
    -hello hello
    +hello goodbye hello
    

    Because the number of times "hello" appears in the file is the same before and after this commit, it will not match using -Shello. However, since there was a change to a line matching hello, the commit will be shown using -Ghello.

提交回复
热议问题