How to grep Git commit diffs or contents for a certain word?

git log's pickaxe will find commits with changes including "word" with git log -Sword


If you want to find all commits where the commit message contains a given word, use

$ git log --grep=word

If you want to find all commits where "word" was added or removed in the file contents (to be more exact: where the number of occurrences of "word" changed), i.e., search the commit contents, use a so-called 'pickaxe' search with

$ git log -Sword

In modern Git there is also

$ git log -Gword

to look for differences whose added or removed line matches "word" (also commit contents).

A few things to note:

  • -G by default accepts a regex, while -S accepts a string, but it can be modified to accept regexes using the --pickaxe-regex.
  • -S finds commits where the number of occurrences of "word" changed, while -G finds commits where "word" appears in the diff.
  • This means that -S<regex> --pickaxe-regex and -G<regex> do not do exactly the same thing.

The git diff documentation has a nice explanation of the difference:

To illustrate the difference between -S<regex> --pickaxe-regex and -G<regex>, consider a commit with the following diff in the same file:

+    return frotz(nitfol, two->ptr, 1, 0);
...
-    hit = frotz(nitfol, mf2.ptr, 1, 0);

While git log -G"frotz\(nitfol" will show this commit, git log -S"frotz\(nitfol" --pickaxe-regex will not (because the number of occurrences of that string did not change).

Tags:

Git

Search

Grep