Skip to main content

grep

Search text by pattern (regex).

Basics

  • Simple search (case-sensitive)
grep 'error' file.log
  • Recursive search in directory
grep -R --line-number 'TODO' src/
  • Case-insensitive, whole word
grep -R -niw 'init' .
  • Show only filenames with matches
grep -Rl 'pattern' .

Context and counts

  • Count matches per file
grep -Rc 'pattern' .
  • Show context lines
grep -R -nC3 'panic' .
# before/after
grep -R -nB2 'panic' .
grep -R -nA2 'panic' .

Regex modes

  • Extended regex (|, +, ?)
grep -E 'foo|bar|baz' file
  • Fixed string (no regex)
grep -F 'a.b' file

Filter pipelines

  • Find JSON lines with status=500 and URL
grep -F '"status":500' app.log | grep -o '"url":"[^"]\+"'

Ignore files/folders

  • Use --exclude, --exclude-dir
grep -R --exclude-dir node_modules --exclude '\*.min.js' 'pattern' .

Color and null-terminated

  • Colorize matches, emit NUL for xargs -0
grep --color=auto -RlZ 'pattern' . | xargs -0 sed -n '1p'