Git grep tips

·

2 min read

If you are working with terminal-based editors like vim, you will need
to search for a text pattern a lot of times. This can be required when
you want to re-factory a symbol and want to find all references to
that symbol in the code.

In order to search for a text in a git repository you can use

git grep

command. This command will search for given text
across all source files in the current repository.

Examples:

git grep Keyword   #will find all lines of code which mention `Keyword`
git grep -A 3 ABCD #same as above but will include 3 lines after each match
git grep -B 3 ABCD  #display 3 lines before each match
git grep -C 3 ABCD   #display 3 lines before and 3 lines after each match
git grep --line-number ABCD #show line-number of each match too
git grep --break ABCD  #put a line break between matches for each file

I normally define this line in my ~/.bashrc file:

git config --global alias.fn    "grep --break --heading --line-number"

So you can simply write

git fn TEXT 

and it will show a
tidy output separated file by file and will group matching in each
source file.