Tour of Git
Advanced Git / Lesson 5.10

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?

Featuregrep -rgit grep
Searches untracked filesYesNo — only tracked files
Respects .gitignoreNoYes
Searches .git directoryCan accidentallyNever
Speed in large reposSlowerOptimized for Git
Search in other branchesNoYes

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

FlagPurposeExample
-nShow line numbersgit grep -n "TODO"
-cCount matches per filegit grep -c "TODO"
-lShow only filenamesgit grep -l "TODO"
-iCase-insensitive searchgit grep -i "todo"
-wMatch whole words onlygit grep -w "log"
-eUse a regex patterngit 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!

  1. 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"
    
  2. Search for all TODOs: git grep "TODO"
  3. Get just the filenames: git grep -l "TODO"
  4. Show line numbers: git grep -n "TODO"
  5. Count matches per file: git grep -c "TODO"
  6. Search only in .js files: git grep "TODO" -- "*.js"

Key Points

  • git grep searches only tracked files, making it faster and more precise than grep -r
  • Use -n for line numbers, -l for filenames only, -c for counts
  • You can search across branches and commits without checking them out
  • Limit searches to specific paths or file types with -- <path>
🎯

Goal

Use git grep to find all files containing the word 'TODO'

Terminal
$

No commits yet. Run `git init` and create your first commit.