LibraryEditorial layoutCompact layout
Browse library

grep

search Edit on GitHub

Search text files and streams for lines that match a pattern.

Version 2.6.0-FreeBSD Updated

grep prints every input line that matches a pattern. It reads named files or standard input, so it works equally well at the end of a pipeline. The cards were checked against macOS grep, which aims for GNU compatibility; differences are noted.

Basic searches

Match precisely

OptionMeaning
-wMatch whole words only
-xMatch whole lines only
-FTreat the pattern as a fixed string
-vPrint lines that do not match

Several patterns

grep -e error -e warning app.log
grep -f patterns.txt app.log

Each -e adds a pattern; -f reads one pattern per line.

Patterns starting with a dash

Tip

grep -e '--verbose' notes.md
grep -- '-v' notes.md

Regular expressions

Pick a syntax

OptionMeaning
-GBasic regular expressions (default)
-EExtended: +, ?, | and () without backslashes
-FNo regex; literal text

Extended examples

grep -E '^(GET|POST) /api/' access.log
grep -E '[0-9]{3}-[0-9]{4}' contacts.txt
grep -E 'colou?r' style-guide.md

Quote patterns in single quotes so the shell leaves |, * and $ alone. More syntax is on the regex sheet.

Print only the match

grep -oE '[a-z0-9.]+@example\.org' users.csv

-o prints each matching part on its own line.

Perl syntax

Note

macOS grep 2.6.0 has no -P option. Use -E, or a grep build that documents -P, for lookarounds and \d.

Files and directories

Search a tree

grep -rn 'TODO' src/
grep -rn --include '*.go' 'context.TODO' .
grep -rn --exclude-dir vendor --exclude-dir .git 'panic(' .

-r recurses into directories; --include and --exclude take file-name globs.

Only file names

OptionMeaning
-lNames of files with at least one match
-LNames of files without a match
-hOmit file names from matching lines
-HAlways show file names

Binary files

grep -I -r 'secret' .
grep -a 'marker' dump.bin

-I skips binary files; -a treats them as text.

Context and counting

Surrounding lines

OptionMeaning
-A 3Three lines after each match
-B 2Two lines before each match
-C 2Two lines on both sides

Count and stop

grep -c 'ERROR' app.log
grep -m 1 '^version' package.toml

-c counts matching lines per file; -m stops after that many matches.

Use in scripts

if grep -q '^ENABLE_CACHE=1$' .env; then
  echo "cache on"
fi

-q prints nothing; exit status is 0 on a match, 1 on no match and above 1 on errors.

Highlight matches

grep --color=auto -n 'deadline' plan.md