grep Search text for lines that match a pattern
Reads files or piped input and prints the lines that match a pattern. Use it to find an error in a log, a word in a set of files, or to filter the output of another command.
Synopsis
grep [OPTION]... PATTERN [FILE]...
command | grep [OPTION]... PATTERN
Common options
| Option or form | What it does |
|---|---|
-i | Ignore case, so error matches Error and ERROR |
-v | Invert the match: print the lines that do not match |
-n | Put the line number in front of each matching line |
-r, -R | Search every file under the given folders. On macOS and BSD, give a folder such as . explicitly |
-c | Print only the number of matching lines, not the lines themselves |
-E | Use extended regular expressions, so | (or), + and ? work without backslashes |
-l | Print only the names of files that contain a match |
-w | Match whole words only, so cat does not match category |
Examples
grep error notes.txt
beta error
error: disk full
grep -in beta notes.txt
2:beta error
4:Beta again
grep -c ERROR app.log
2
grep -v error notes.txt
alpha
gamma
Beta again
delta
grep -rl ERROR .
./app.log
grep -E 'ERROR|WARN' app.log
2026-01-01 ERROR failed to open
2026-01-02 WARN slow
2026-01-02 ERROR timeout
Notes
- Exit status: 0 if at least one line matched, 1 if nothing matched, 2 if there was an error such as a missing file. Scripts use this, for example: grep -q fig words.txt && echo found. The -q flag prints nothing and only sets the status.
- Put the pattern in quotes when it has spaces, *, | or $. Otherwise the shell changes it before grep sees it.
- Plain grep uses basic regular expressions. Characters such as + and | have no special meaning unless you add -E. On macOS, the backslash form \+ is not reliable, so use -E instead.
- To search for text exactly as typed, with no pattern characters, use -F. Use -o to print only the matched part, and -A, -B or -C with a number to show lines around each match.
- With more than one file, grep puts the file name in front of each line. Use -h to hide it, or -H to show it for a single file.
See also
Last reviewed 2026-10-07.