Select Page

Introduction

Use git grep to search code within the git repo. It makes it very convenient and efficient to do code searches without leaving your terminal (or editor).

Setup Git Repo

Setting up a sample git repo to play with git grep.
git init someproject
cd someproject
echo -e ""# Git Grep\n"" > info.md
echo -e ""Git grep is a powerful handy tool to search code within a git repo."" > info.md
git add info.md
git commit -m ""Add info file”
Output after the final command.
[main (root-commit) 2d587a0] Add info file
1 file changed, 3 insertions(+)
create mode 100644 info.md

This is a good enough setup for us to play with git grep;.

Git Grep

Search the desired term

git grep <term>
Example
git grep Grep
# Output:
# info.md:# Git Grep
Example
git grep grep
# Output:
# info.md:Git grep is a powerful handy tool to search code within a git repo.

Enable line numbers in the search result

Search with -n flag.

Example

git grep -n Grep
# Output:
# info.md:1:# Git Grep

Example

git grep -n grep
# Output:
# info.md:3:Git grep is a powerful handy tool to search code within a git repo.

Before and after context

Use -A<num> for after context, `-B<num>` for before context, and `-C<num>` for context lines before and after both.
Example
git grep -n -A2 Grep
# Output:
# info.md:1:# Git Grep
# info.md-2-
# info.md-3-Git grep is a powerful handy tool to search code within a git repo.
The shorthand for the `-C<num>` context lines is `-<num>`.
Example
git grep -2 Grep
# Output:
# info.md:# Git Grep
# info.md-
# info.md-Git grep is a powerful handy tool to search code within a git repo.

Matching file names only

Using flag `-l` to only see the list of matching file names.
Example
git grep -l Grep
# Output:
# info.md

Case-insensitive search

Use `-i` to make your search case-insensitive.

Example
git grep -i Grep
# Output:
# info.md:# Git Grep
# info.md:Git grep is a powerful handy tool to search code within a git repo.

Search multiple terms at once

Use pattern search with flag `-e` as `-e<pattern>`.
Example
git grep -e grep -e Grep
# Output:
# info.md:# Git Grep
# info.md:Git grep is a powerful handy tool to search code within a git repo.

Search can be limited to a file or directory

Example
git grep Grep info.md
# Output:
# info.md:# Git Grep

Conclusion

There are many more features packed into git grep, like inverted search, regex search, recursive search within sub-directories, number of matches in the file, etc.