← Full reference

grep

Search for lines matching a pattern in files and command output

grep reads files (or standard input) line by line and prints the lines where the pattern is found. The pattern is a regular expression or, with -F, a plain string. The sandbox has GNU grep 3.11.

Syntax

grep [options] 'pattern' [file…]
grep [options] -e 'pattern1' -e 'pattern2' [file…]
command | grep [options] 'pattern'

Without files grep reads stdin (with -r — the current directory). The file - also means stdin.

Exit code: 0 — at least one line found, 1 — nothing found, 2 — error (missing file, invalid regex). With -q, a match gives 0 even if some file couldn't be read.

Options

How to interpret the pattern

OptionWhat it does
-Gbasic regexes (BRE) — the default mode
-Eextended regexes (ERE): + ? | ( ) { } without backslashes
-Fthe pattern is a plain string, no special characters
-PPerl regexes (PCRE): \d, \s, lazy *?, lookaround (?=…), \K
-e patternspecify a pattern; can be repeated — matches any. Needed if the pattern starts with -
-f filetake patterns from a file, one per line
-icase-insensitive; --no-ignore-case — undo
-wthe pattern must match a whole word (a word is letters, digits, _)
-xthe pattern must match the entire line
-vselect lines that do not match

What and how to print

OptionWhat it does
-cinstead of lines — their count (matching lines, not matches), per file
-l / -Lonly names of files that have a match / that don't
-oonly the matched fragments, each on its own line
-qprint nothing, only the exit code; stops at the first match
-nline number before the line: 12:text
-bbyte offset from the start of the file
-H / -hprint / don't print the file name before the line. By default the name is shown if there's more than one file (or -r)
-m Nstop after N matching lines in each file
-sdon't report missing and unreadable files
--color=autohighlight matches (always — even in a pipeline)
--line-bufferedflush output after each line — needed in tail -f … | grep …
-Zput a null byte after the file name (for xargs -0)
-Talign output with a tab after the prefixes
--label=namename to show for stdin

Context

OptionWhat it does
-A Nshow N more lines after the match
-B Nshow N lines before the match
-C N / -NN lines before and after (-2 is the same as -C 2)
--group-separator=STR / --no-group-separatorwhat separates context groups (default --) / no separator

Files and directories

OptionWhat it does
-rsearch directories recursively; doesn't follow symbolic links inside
-Rsame, but follows all symbolic links
--include='*.conf'look only at files matching the mask (can be repeated)
--exclude='*.log'skip files by mask
--exclude-dir=.gitdon't descend into directories by mask
-atreat a binary file as text and print matching lines
-Isilently skip binary files
-zlines are separated by a null byte, not \n (for find -print0 output)

Output format

An output line is built from prefixes: file_name:number:offset:text. Context lines (-A/-B/-C) are separated not by : but by - (app.log-14-text), and -- is printed between non-adjacent groups.

Examples

printf 'INFO start\nERROR disk full\nWARN slow\nerror retry\nINFO stop\n' > app.log

# lines with error in any case, with numbers
grep -in error app.log

# everything except INFO lines
grep -v INFO app.log

# several patterns: via -E and | or via several -e
grep -E 'ERROR|WARN' app.log
grep -e ERROR -e WARN app.log

# patterns from a file
printf 'ERROR\nWARN\n' > patterns.txt
grep -f patterns.txt app.log

# how many lines matched and how many occurrences in total
grep -ci error app.log
grep -oi error app.log | wc -l

# context: the WARN line, one before and one after
grep -C1 WARN app.log

# a dot as a dot, not "any character"
printf 'v1.2.3\nv1x2y3\n' | grep -F '1.2.3'

# whole word and whole line
printf 'cat\ncatalog\nthe cat\n' | grep -w cat
printf 'cat\ncatalog\nthe cat\n' | grep -x cat

# recursively: only *.conf, skipping .git, file names only
grep -rl --include='*.conf' --exclude-dir=.git 'listen' /etc

# in a script condition
if grep -q '^ERROR' app.log; then echo 'there are errors'; fi

# the value after a key: \K drops everything matched before it
echo 'port=8080' | grep -oP 'port=\K\d+'

# only the first match
grep -m1 INFO app.log

# names of files with matches — safe for xargs
grep -rlZ 'listen' /etc/nginx | xargs -0 ls -l

Pitfalls

  • -c counts lines, not matches. The line error error counts as 1. Count every occurrence with grep -o … | wc -l.
  • ps aux | grep nginx also finds grep itself. Put one letter in brackets — grep '[n]ginx': the pattern still matches nginx, but grep's own command line ([n]ginx) no longer does. Even simpler — pgrep.
  • Basic regexes (without -E) treat + ? | ( ) { } literally. grep 'a+b' searches for the string a+b. Write grep -E 'a+b' or grep 'a\+b'. More — Regular expressions.
  • \d and \t work only with -P. Without it \d is just the letter d, and \t is the letter t. For digits there's [0-9] or [[:digit:]]; a tab can be passed as $'\t'.
  • An unquoted pattern is expanded by the shell: *, ?, […] and $ may change before grep even starts. Put the pattern in single quotes.
  • -r doesn't follow symbolic links inside a directory, -R does. Quote the --include and --exclude masks too.
  • Binary files. If a file contains null bytes, grep prints binary file matches instead of the line. -a shows the lines, -I skips such files.
  • -o with -c still counts lines, and -o together with -v prints nothing.
  • Locale. The sandbox locale is POSIX, so -i doesn't compare non-ASCII letters case-insensitively (Éclair and éclair differ), and . matches a single byte rather than a multibyte letter like é. With LC_ALL=C.utf8 both cases work as expected.

See also

Regular expressions · sed · awk · find · xargs · wc