How to find the Git commit introducing a given change into a file

Continuing last month’s theme of searching Git history — here we look at how to find the source of changes, even after other people have worked on (or reformatted) the area in question.

The question:  which commit actually introduced a given string into the file?

The ‘git log’ command can help us here. To search for “searchString” in a given file:

git log --source -S 'searchString' -- path/to/my/File.java

The same search throughout all files in the repository:

git log --source -S 'searchString' --all

As well as -S for simple search, you can use -G for regex; this is also more accurate as it detects lines moved in the file (-S doesn’t).

git log --source -G 'search\w+String' -- path/to/my/File.java

Use -p to view the diff of each change.

git log --source -p -G 'search\w+String' -- path/to/my/File.java

References:
- Stack Overflow: Finding a Git commit that introduced a string in any branch
- Git Tip of the Week: Searching for Commits and Changes
- ‘git log’ documentation

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>