grep Flags Reference

Every grep / egrep / fgrep flag with description and POSIX/GNU flavor note.

Searchable grep flag reference covering matching control (-i, -v, -w, -F), output (-c, -l, -o, -n), context (-A, -B, -C), recursive file selection (-r, --include) and regex flavors (-E, -P), each with a POSIX or GNU note.

What is the difference between grep, egrep and fgrep?

They are the same program with different default regex modes. grep uses basic regular expressions, egrep is equivalent to grep -E for extended regex, and fgrep is grep -F for fixed literal strings. The egrep and fgrep names are deprecated in favour of the flags.

grep flags

grep searches text for lines matching a pattern and prints them. Its behaviour is shaped almost entirely by flags: whether matching is case-sensitive, what counts as a match, how results are reported, how much context is shown, which files are searched recursively, and which regular-expression dialect applies. This page is a searchable, offline reference to every common grep flag, with a note on whether each is POSIX-standard or a GNU extension.

How it works

grep reads input line by line and tests each line against the pattern. Flags fall into clear groups:

  • Matching control changes what matches: -i ignores case, -v inverts, -w and -x require whole-word or whole-line matches, and -F treats the pattern as a literal string instead of a regex.
  • Output control changes what is printed: -c counts, -l/-L list file names, -o prints only the matched text, -n adds line numbers, and -q prints nothing but sets the exit status.
  • Context flags -A, -B, -C print surrounding lines.
  • File selection flags -r/-R recurse, while --include, --exclude and --exclude-dir filter which paths are searched.
  • Regex flavor is chosen with -G (basic, default), -E (extended) or -P (Perl/PCRE).

The exit status is itself useful: 0 means at least one match, 1 means no match, and 2 means an error.

Tips and examples

Find all TODO comments under a source tree, but only in JavaScript files:

grep -rn --include='*.js' 'TODO' src/

Count how many lines mention an error, case-insensitively:

grep -ic 'error' app.log

Show three lines of context around each match to read it in situ:

grep -C3 'panic' server.log

Use grep purely as a condition without printing anything:

if grep -qF "feature_x" config.ini; then
  echo "feature enabled"
fi

Prefer -F whenever your search text is a fixed string with regex metacharacters like dots or brackets — it is both faster and avoids surprises.