I have 2 different branches A,B that have a (slightly different) version of a file X.
I am interested in getting the commits that added some specific patterns in branch B.
What I do roughly: diff files| grep "^\+" | grep "$PATTERN" | for loop grep -n.. do git blame -L done
This works but I was wondering if I am re-inventing/going a roundabout for something that is readily supported in git.
Is there a better way?


I think you can combine git blame and git merge-base to get the information you’re after:

git blame -n $(git merge-base A B).. -- file | grep -v "^^" | grep "$PATTERN"

This finds the common ancestor between A and B, then runs git blame on file, ignoring anything older than the common ancestor (the .. notation tells git blame to look at revisions starting with the ancestor and ending at the current head). -n adds line numbers in the output. Then grep -v "^^" removes any lines which haven’t changed since the common ancestor, and finally grep "$PATTERN" looks for the pattern among only the lines which have changed. Since git blame in non-reverse mode only shows the lines currently in the file, the results will only include added or modified lines, which is exactly equivalent to your ^\+ filter.

  • 1) What are the .. after ` $(git merge-base A B)? 2) Also when you say changed you mean added/deleted/modified`? Because I am interested only in additions – Jim Jun 7 '18 at 22:33
  • This command verbatim gives the same output as my approach but I still don't get how it produces exactly the additions – Jim Jun 7 '18 at 22:36
  • I’ve expanded a little to address those questions. Note that your approach, as well as mine, include both added and modified lines; in your approach, modified lines are included because they appear as a - line (the old contents) followed by a + line (the new contents). – Stephen Kitt Jun 7 '18 at 22:50
  • Where in git blame --help shows this option and that ^^ is for non-modified entries? – Jim Jun 8 '18 at 7:33
  • It’s not particularly obvious; see the description of --abbrev, and in particular “Note that 1 column is used for a caret to mark the boundary commit.” The indicator isn’t ^^, it’s a single ^; the grep filter is ^^ to filter on ^ at the start of a line (the first ^ is the beginning-of-line anchor, the second ^ is the caret we’re looking for). – Stephen Kitt Jun 8 '18 at 7:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.