Skip to content

Drill: Code Search with ripgrep (rg)

Goal

Use ripgrep for fast code search with file type filters, context lines, multiline patterns, and glob-based exclusions.

Setup

  • Install ripgrep (apt install ripgrep, brew install ripgrep, or download from GitHub)
  • A codebase or directory to search

Commands

Basic search:

rg "TODO" .

Case-insensitive search:

rg -i "error" .

Search with context lines (before/after):

rg -C 3 "panic" .        # 3 lines before and after
rg -B 2 -A 5 "func main" . # 2 before, 5 after

Filter by file type:

rg --type py "import requests"
rg --type go "func.*Handler"
rg --type yaml "apiVersion"

List available types:

rg --type-list

Search with glob patterns:

rg "password" -g '*.yaml' -g '!*test*'

Search for a fixed string (no regex):

rg -F "fmt.Println(" .

Show only filenames:

rg -l "TODO" .

Count matches per file:

rg -c "import" --type py

Search for multiline patterns:

rg -U "func.*\n.*error" --type go

Invert match (lines NOT containing pattern):

rg -v "^#" /etc/ssh/sshd_config

Search with word boundaries:

rg -w "port" .  # matches "port" but not "export" or "portal"

Use custom file type definitions:

rg --type-add 'helm:*.tpl' --type helm "{{" .

What to Look For

  • rg respects .gitignore by default (use --no-ignore to override)
  • File type filters save time over manual glob patterns
  • -U enables multiline mode for patterns spanning line boundaries
  • --json output can be piped to jq for programmatic processing

Common Mistakes

  • Forgetting that rg skips .gitignored files by default
  • Not using -F for literal strings containing regex metacharacters
  • Using -g '*.py' without the quotes, causing shell glob expansion
  • Not using -w and getting false positives from partial word matches

Cleanup

No cleanup needed. rg is a read-only search tool.