git blame of particular lines inside all files filtered with grep command

4.4k Views Asked by At

I know how to run gblame inside a file.

I know how to grep a content inside all files in a directory.

I'd like to see gblame of particular lines around that one that contains a content. Example:

$ blame -R "content" ./

I see a list of files. I want to gblame all of theme, and understand who has touched those lines of code.

3

There are 3 best solutions below

3
On BEST ANSWER

You can do it with Perl:

git grep -n 'content' | perl -F':' -anpe '$_=`git blame -L$F[1],+1 $F[0]`'

and if you want to create a custom command you can add something like this to your gitconfig in the alias section:

gb = "!f() { git grep -n $1 | perl -F':' -anpe '$_=`git blame -L$F[1],+1 $F[0]`'; }; f"
1
On

find files with needle, for each file blame, and for each blame output search needle

for file in `grep -lr needle *`; do  git blame $file |grep needle ; done

You can add context with -C

for file in `grep -lr needle *`; do  git blame $file |grep -C5 needle ; done
1
On

I wrote this little script to accomplish git grep + blame:

#!/bin/bash

if [ "$1" = "" ] ; then
    echo "usage: $0 <term>" 1>&2
    exit 1
fi

for file in $(git grep $1 | cut -d ':' -f 1 | uniq) ; do
    echo $file ::
    git blame $file | grep $1
done