11

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.

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
sensorario
  • 20,262
  • 30
  • 97
  • 159

3 Answers3

23

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"
Cash Lo
  • 1,052
  • 1
  • 8
  • 20
  • For me, the first command did not display the file name. How can the command be extended to display the filename? – Arun Mar 20 '18 at 23:50
  • 2
    @Arun You can use the -f / --show-name option for blame, which will show you file names, so the command would be: `git blame -fL$F[1],+1 $F[0]` – Cash Lo Apr 04 '18 at 15:08
  • I ended up using `git blame -lf $F[1],+1 $F[0] | | git name-rev --stdin --tags --always` in order to see the closest release tag. – Dan Berindei May 22 '20 at 05:10
0

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
Ôrel
  • 7,044
  • 3
  • 27
  • 46
0

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 
davebrown
  • 9
  • 2
  • I modified this to be .bash_profile addable by kicking out the #!/bin/bash and just writing function ggb { your content } . works like a charm. nice! Thanks for sharing this. – esaruoho Sep 22 '20 at 21:50