git grep — Searching Code
git grep searches for text patterns across your tracked files. Unlike regular grep, it only searches files that Git knows about, automatically respects .gitignore, and is optimized for speed in repositories.
Why git grep Instead of Regular grep?
| Feature | grep -r | git grep |
|---|---|---|
| Searches untracked files | Yes | No — only tracked files |
| Respects .gitignore | No | Yes |
| Searches .git directory | Can accidentally | Never |
| Speed in large repos | Slower | Optimized for Git |
| Search in other branches | No | Yes |
Basic Usage
git grep "TODO"
This searches all tracked files in the working directory for the string "TODO" and prints matching lines with filenames.
Useful Flags
| Flag | Purpose | Example |
|---|---|---|
-n | Show line numbers | git grep -n "TODO" |
-c | Count matches per file | git grep -c "TODO" |
-l | Show only filenames | git grep -l "TODO" |
-i | Case-insensitive search | git grep -i "todo" |
-w | Match whole words only | git grep -w "log" |
-e | Use a regex pattern | git grep -e "TODO|FIXME" |
Combining Flags
Find all TODO comments with line numbers, case-insensitive:
git grep -n -i "todo"
Just want to know which files contain the pattern?
git grep -l "config"
Count how many matches each file has:
git grep -c "import"
Searching in Specific Commits or Branches
One of git grep's superpowers is searching in any commit or branch — without checking it out:
# Search in a specific branch
git grep "database" feature/auth
# Search in a specific commit
git grep "database" abc1234
# Search in the previous commit
git grep "database" HEAD~1
This is incredibly useful for questions like "Did we have this string in the last release?"
Searching Specific Paths
Limit the search to certain directories or file types:
# Only search in the src directory
git grep "TODO" -- src/
# Only search JavaScript files
git grep "TODO" -- "*.js"
# Exclude test files
git grep "TODO" -- ':!tests/'
Try it!
- Create a few files with some content:
echo "TODO: fix login bug" > notes.txt echo "function login() { return true; }" > app.js echo "TODO: add tests" >> app.js git add notes.txt app.js git commit -m "Add project files" - Search for all TODOs:
git grep "TODO" - Get just the filenames:
git grep -l "TODO" - Show line numbers:
git grep -n "TODO" - Count matches per file:
git grep -c "TODO" - Search only in
.jsfiles:git grep "TODO" -- "*.js"
Key Points
git grepsearches only tracked files, making it faster and more precise thangrep -r- Use
-nfor line numbers,-lfor filenames only,-cfor counts - You can search across branches and commits without checking them out
- Limit searches to specific paths or file types with
-- <path>