my-notes

git_grep

1 min read

git grep

Search code within your repository.


Search in Working Directory

git grep "search term"

Searches tracked files for term.


Case Insensitive

git grep -i "search"

Ignores case.


Show Line Numbers

git grep -n "search"

Shows line numbers with results.


Show Only Filenames

git grep -l "search"

Lists only matching files.


Count Matches

git grep -c "search"

Shows count of matches per file.


🎯 Pattern Matching

git grep -e "pattern.*match"

Uses regex pattern.


Extended Regex

git grep -E "pattern|alternative"

Extended regex (OR patterns).


Word Match

git grep -w "function"

Matches whole word only.


πŸ“ Limit Scope

Search Specific Files

git grep "search" -- "*.js"

Only searches JavaScript files.


Search Directory

git grep "search" -- src/

Only searches in src/ directory.


Exclude Path

git grep "search" -- ':!node_modules'

Excludes node_modules.


⏰ Search History

Search at Commit

git grep "search" abc1234

Searches in specific commit.


Search Across Branches

git grep "search" main develop feature

Searches in multiple branches.


Search All Branches

git grep "search" $(git rev-list --all)

Searches entire history.


πŸ“Š Output Options

Show Context

git grep -C 3 "search"

Shows 3 lines context around matches.


Before Context

git grep -B 2 "search"

Shows 2 lines before match.


After Context

git grep -A 2 "search"

Shows 2 lines after match.


Match Multiple Terms

git grep -e "term1" --and -e "term2"

Both terms must appear in same file.


Match Either Term

git grep -e "term1" --or -e "term2"

Either term matches.


Complex Boolean

git grep -e "term1" --and \( -e "term2" --or -e "term3" \)

Complex pattern matching.


πŸ’‘ Tips

vs Regular grep

git grep is faster because it only searches tracked files.

Find Function Definition
git grep -n "function searchName"
Find TODO Comments
git grep -n "TODO:"


#git #grep #search #advanced

Built with mdgarden