C.W.K.
Stream
Lesson 07 of 10 · published

grep and ripgrep

~10 min · grep, ripgrep, shell

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

The terminal's regex tool

For shell-level text searching, the canonical tool was grep. The modern replacement is ripgrep (rg) — written in Rust, uses RE2-class engine, recursive by default, respects .gitignore, blazing fast.

grep flavors

POSIX grep has three modes that differ in how they treat metacharacters:

  • BRE (default): ?, +, {}, (), | are LITERAL unless escaped. grep 'foo\(bar\)'
  • ERE (grep -E or egrep): Modern syntax — those metacharacters work without escaping. grep -E 'foo(bar)'
  • PCRE (grep -P): Full Perl-compatible. Lookaround, backreferences, named groups. Not always available (depends on grep build).

Use -E by default. Use -P when you need PCRE features. Avoid plain grep with regex — too many gotchas.

ripgrep — the modern default

rg uses RE2-style syntax (no lookaround, no backreferences, but linear time). It's recursive by default, respects .gitignore, supports Unicode well, and is dramatically faster than grep on large codebases.

Common flags:

  • rg pattern — search recursively in current directory
  • rg -i pattern — case-insensitive
  • rg -n pattern — show line numbers (default in interactive mode)
  • rg -l pattern — list only filenames with matches
  • rg -A 3 pattern — show 3 lines of context after each match
  • rg --pcre2 pattern — enable PCRE2 (lookaround, backreferences)
  • rg -r 'replacement' pattern — preview replacements ($1, $2 for groups)

Code

grep vs ripgrep·bash
# POSIX grep BRE — escaping required
grep 'foo\(bar\)' file.txt

# grep ERE — modern
grep -E 'foo(bar)' file.txt

# grep PCRE — full features (when available)
grep -P '(?<=user_)\w+' file.txt

# ripgrep — recursive by default, respects .gitignore
rg 'TODO|FIXME' .

# ripgrep with line numbers and case insensitive
rg -ni 'error' logs/

# ripgrep with PCRE for lookaround
rg --pcre2 '(?<=password = )\S+' config/

# Preview a replacement
rg -r 'NEW: $1' '(\d+)' file.txt

# Find files containing a pattern
rg -l 're.compile' .

# Search only specific file types
rg -t py 'import re' .

External links

Exercise

Install ripgrep if you don't have it (brew install ripgrep on macOS). Run rg 'TODO' . in a code project. Then rg -t py 'import re' . to find every Python file using regex. Compare with the equivalent grep -r command.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.