How to search text with grep in Linux

· Category: Linux

Short answer

grep searches for patterns in text files and streams, supporting regex, line numbers, and context display.

Steps

  1. Search a file:
grep "error" log.txt
  1. Case-insensitive search:
grep -i "error" log.txt
  1. Recursive search:
grep -r "pattern" /var/log/
  1. Show line numbers:
grep -n "pattern" file.txt
  1. Invert match:
grep -v "pattern" file.txt

Tips

  • grep -E (or egrep) enables extended regular expressions.
  • grep -C 2 shows 2 lines of context around each match.
  • Pipe ps or df into grep to filter output.

Common issues

  • Binary files: use -I to ignore or -a to treat as text.
  • Recursive symlink loops: use --exclude-dir or -R instead of -r.