0
0
GitHow-ToBeginner · 3 min read

How to Use git grep: Search Code in Git Repositories

Use git grep <pattern> to search for a text pattern inside files tracked by Git. It shows matching lines with filenames, helping you quickly find code or text in your repository.
📐

Syntax

The basic syntax of git grep is:

  • git grep <pattern>: Search for the pattern in tracked files.
  • git grep <pattern> -- <path>: Search only in files under the specified path.
  • git grep -n <pattern>: Show line numbers of matches.
  • git grep -i <pattern>: Search case-insensitively.
bash
git grep <pattern>
git grep <pattern> -- <path>
git grep -n <pattern>
git grep -i <pattern>
💻

Example

This example searches for the word TODO in all tracked files and shows the filename and matching line:

bash
git grep TODO
Output
src/app.js:45:// TODO: Refactor this function README.md:12:<!-- TODO: Add installation instructions -->
⚠️

Common Pitfalls

1. Searching untracked files: git grep only searches files tracked by Git, so new untracked files won't be searched.

2. Forgetting to quote patterns: If your pattern contains special characters or spaces, wrap it in quotes to avoid shell issues.

3. Confusing git grep with grep: git grep searches only tracked files and respects Git settings, unlike regular grep.

bash
Wrong:
git grep TODO items

Right:
git grep "TODO items"
📊

Quick Reference

OptionDescription
<pattern>Text or regex pattern to search for
-nShow line numbers with matches
-iIgnore case when searching
-- <path>Limit search to files under the given path
-vShow lines that do NOT match the pattern

Key Takeaways

Use git grep <pattern> to quickly find text in tracked files.
Wrap patterns in quotes if they contain spaces or special characters.
git grep only searches files tracked by Git, not untracked files.
Use options like -n for line numbers and -i for case-insensitive search.
Limit search to specific folders with -- <path>.