Viewing and processing text

Command grep

Search strings by pattern

Linux · Bash examples · commands run on the selected server

When to use grep

Use grep to select matching lines from files or command output. Decide whether your search is a regular expression or literal text, and narrow recursive searches to relevant files.

Syntax

grep [OPTIONS] TEMPLATE [FILE...]

Square brackets mark optional arguments; an ellipsis means repetition. Replace example file names, user names and server addresses with your own values.

Common options and arguments

-n
Show the number of the matched line.
-i
Case insensitive search.
-F
Treat the pattern as a regular string rather than a regular expression.

Usage examples

Find errors in the log

grep -n 'ERROR' ./app.log

Matching log lines are printed with their line numbers.

Search in the project tree

grep -Rni --include='*.conf' 'listen' ./config

Configuration files are searched recursively without matching case; other filename types are excluded.

Find exact text

grep -F -- 'user@example.com' ./users.txt

The address is matched as literal text, so punctuation does not act as a regular expression.

Notes and limitations

  • For a pattern with a leading hyphen, use -- or -e.
  • Code 1 means no match, not a read error; binary files are processed separately.

Common questions and troubleshooting

Why does grep return status 1?

The command found no matching lines. In scripts, handle an empty match result separately from file access errors and invalid patterns.

How do I search a pattern containing punctuation?

Use fixed-string mode when you want exact text. Quote the pattern and end option parsing when a pattern might begin with a hyphen.

Further help

Options vary by version and distribution. Check the installed documentation with this command: man grep.