iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

grep

grep finds lines that match a pattern. ripgrep (rg) is the modern replacement — faster, smarter defaults, respects .gitignore.

grep + ripgrep that pays off

EXAMPLE
# 1) Basics
grep 'ERROR' app.log
grep -i 'error' app.log              # case-insensitive
grep -n 'TODO' src/**/*.js           # show line numbers
grep -c 'WARN' app.log               # count matches
grep -v 'DEBUG' app.log              # INVERT — exclude
grep -l 'TODO' src/*.js              # list FILES containing match
grep -L 'license' src/*.js           # list files NOT containing
grep -w 'id' file                    # whole-word
grep -r 'api_key' .                  # recursive

# 2) Context — see the surrounding lines
grep -B 2 -A 2 'panic' /var/log/syslog
grep -C 5 'OOM' /var/log/kern.log

# 3) Regex flavours
grep 'foo.bar' file                  # BRE (default)
grep -E 'foo|bar|baz' file           # ERE — alternation
grep -P '(?<=name=)\w+' file         # Perl-compatible (lookahead!)
grep -F 'literal[.string]' file      # FIXED — no regex magic

# 4) Output only the match
grep -o 'https?://[^"]*' page.html   # extract URLs
grep -oE '[0-9]{4}-[0-9]{2}-[0-9]{2}' log

# 5) Use with pipes
ps aux | grep -v grep | grep node
history | grep ssh | tail

# 6) ripgrep — the modern default
rg 'TODO'                            # recursive by default, honours .gitignore
rg -i 'todo'
rg -t py 'def authenticate'          # only .py files
rg -g '!*.test.ts' 'fetch('          # exclude tests
rg 'pattern' -A 3 -B 1               # context
rg -F 'literal[.string]'             # fixed string
rg 'apiKey' -l                       # files only
rg -c 'ERROR'                        # count per file
rg 'foo|bar' --multiline

# 7) Common one-liners
# Find files that import a removed module
rg -l 'from "old-lib"' src/
# Pull all email addresses from a log
rg -oE '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}' app.log | sort -u
# Replace + edit (rg's sed-style with --files-with-matches)
rg -l 'foo' | xargs sed -i 's/foo/bar/g'

Why it matters

ripgrep respects .gitignore + parallelises automatically — the default behaviour you actually want. Reach for grep only when you need POSIX portability.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
grep -RIn 'TODO' src/
grep -E 'ERR|WARN' app.log
Try it Yourself »

Exercise

Recursive case-insensitive grep with line numbers.

grep 'TODO' src/

Discussion

Loading…