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
| Option | What it does |
|---|---|
-G | basic regexes (BRE) — the default mode |
-E | extended regexes (ERE): + ? | ( ) { } without backslashes |
-F | the pattern is a plain string, no special characters |
-P | Perl regexes (PCRE): \d, \s, lazy *?, lookaround (?=…), \K |
-e pattern | specify a pattern; can be repeated — matches any. Needed if the pattern starts with - |
-f file | take patterns from a file, one per line |
-i | case-insensitive; --no-ignore-case — undo |
-w | the pattern must match a whole word (a word is letters, digits, _) |
-x | the pattern must match the entire line |
-v | select lines that do not match |
What and how to print
| Option | What it does |
|---|---|
-c | instead of lines — their count (matching lines, not matches), per file |
-l / -L | only names of files that have a match / that don't |
-o | only the matched fragments, each on its own line |
-q | print nothing, only the exit code; stops at the first match |
-n | line number before the line: 12:text |
-b | byte offset from the start of the file |
-H / -h | print / 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 N | stop after N matching lines in each file |
-s | don't report missing and unreadable files |
--color=auto | highlight matches (always — even in a pipeline) |
--line-buffered | flush output after each line — needed in tail -f … | grep … |
-Z | put a null byte after the file name (for xargs -0) |
-T | align output with a tab after the prefixes |
--label=name | name to show for stdin |
Context
| Option | What it does |
|---|---|
-A N | show N more lines after the match |
-B N | show N lines before the match |
-C N / -N | N lines before and after (-2 is the same as -C 2) |
--group-separator=STR / --no-group-separator | what separates context groups (default --) / no separator |
Files and directories
| Option | What it does |
|---|---|
-r | search directories recursively; doesn't follow symbolic links inside |
-R | same, 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=.git | don't descend into directories by mask |
-a | treat a binary file as text and print matching lines |
-I | silently skip binary files |
-z | lines 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
-ccounts lines, not matches. The lineerror errorcounts as 1. Count every occurrence withgrep -o … | wc -l.ps aux | grep nginxalso findsgrepitself. Put one letter in brackets —grep '[n]ginx': the pattern still matchesnginx, 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 stringa+b. Writegrep -E 'a+b'orgrep 'a\+b'. More — Regular expressions. \dand\twork only with-P. Without it\dis just the letterd, and\tis the lettert. 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. -rdoesn't follow symbolic links inside a directory,-Rdoes. Quote the--includeand--excludemasks too.- Binary files. If a file contains null bytes, grep prints
binary file matchesinstead of the line.-ashows the lines,-Iskips such files. -owith-cstill counts lines, and-otogether with-vprints nothing.- Locale. The sandbox locale is
POSIX, so-idoesn't compare non-ASCII letters case-insensitively (Éclairandéclairdiffer), and.matches a single byte rather than a multibyte letter likeé. WithLC_ALL=C.utf8both cases work as expected.