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: Git search for string in a single files history
– 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