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:
-iignores case,-vinverts,-wand-xrequire whole-word or whole-line matches, and-Ftreats the pattern as a literal string instead of a regex. - Output control changes what is printed:
-ccounts,-l/-Llist file names,-oprints only the matched text,-nadds line numbers, and-qprints nothing but sets the exit status. - Context flags
-A,-B,-Cprint surrounding lines. - File selection flags
-r/-Rrecurse, while--include,--excludeand--exclude-dirfilter 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.