Terminal · foundation

Text search with grep

grep reads text input, tests each line against one or more patterns, and normally writes selected lines to standard output.

Why it matters

grep is a fast, composable filter for logs and source, but correct use depends on pattern mode, binary input, filenames, and its three-way status contract.

Mental model

How to reason about text search with grep

For each input line, grep applies its selected matcher and emits the line when the selection condition holds; flags alter matching, selection, and presentation separately.

Analogy

It is a checkpoint that lets matching records continue down the pipeline while optionally labeling where each accepted record came from.

Examples

See the boundary, not just the happy path

Worked example · Fixed-string recursive search

grep -RFn -- 'user[id]' src

-F treats metacharacters literally, -R traverses recursively, -n reports line numbers, and -- protects a dash-prefixed pattern.

Worked example · Quiet predicate

if grep -q '^READY$' status.txt; then deploy; fi

-q suppresses selected-line output because the shell needs only grep's status; the anchored basic regex requires the entire line to be READY.

Useful contrast · Literal versus regular expression

grep -F 'a.*b' data.txt

With -F, a.*b is searched as five literal characters; without -F, . and * participate in regular-expression matching.

Common mistakes

Misconceptions to remove early

Using a regex when the text should be literal

Unescaped metacharacters can widen the match; -F is clearer and safer when no pattern language is needed.

Parsing filenames from ordinary recursive output

Filenames can contain separators and newlines; use purpose-built null-delimited options where supported when output must be machine-consumed.

Quick check

Can you predict the result?

1. Which grep option selects fixed-string matching?
  • -F
  • -E
  • -n
Answer: -F
2. Why is grep -q useful inside an if statement?
Answer: It suppresses matching output while preserving the documented status used by the conditional.

Keep building

Authoritative references

Make the idea retrievable.

Study this concept with spaced repetition, next to the commands where you use it.

Get Terminaster