Skip to content

grep

21 commands

Searches text for lines matching a pattern, with regular expressions, recursion and context.

  • search
  • regex
  • text

Install grep

sudo apt install grep

Basics7

grep "<pattern>" <file>

Prints every line containing the pattern.

Link
grep -i "<pattern>" <file>

Case-insensitive match.

Link
grep -v "<pattern>" <file>

Inverts the match: prints lines that do not contain the pattern.

Link
grep -n "<pattern>" <file>

Prefixes each match with its line number.

Link
grep -c "<pattern>" <file>

Counts matching lines instead of printing them.

Link
grep -w "<word>" <file>

Matches whole words only, so “root” does not match “chroot”.

Link
grep -x "<line>" <file>

Matches only if the entire line is the pattern.

Link

Searching trees5

grep -r "<pattern>" <dir>

Searches every file under a directory recursively.

Link
grep -rl "<pattern>" <dir>

Lists only the names of files that match.

Link
grep -rn --include="<glob>" "<pattern>" <dir>

Restricts the search to certain file types.

Link
grep -r --exclude-dir=<dir> "<pattern>" .

Skips directories you do not care about.

Link
grep -rIl "<pattern>" <dir>

Skips binary files (-I) — here hunting for private keys left on disk.

Link

Patterns5

grep -E "<a>|<b>" <file>

Extended regular expressions: alternation, +, ? and {n} without backslashes.

Link
grep -o "<regex>" <file>

Prints only the matched part of each line — here, every IPv4 address.

Link
grep -F "<string>" <file>

Treats the pattern as a fixed string, not a regex — faster and no escaping.

Link
grep -P "<regex>" <file>

Perl-compatible regex with \d, lookarounds and lazy quantifiers (GNU grep).

Link
grep -f <patterns> <file>

Reads many patterns from a file, one per line — handy for IOC matching.

Link

Context4

grep -A <n> "<pattern>" <file>

Shows n lines after each match.

Link
grep -B <n> "<pattern>" <file>

Shows n lines before each match.

Link
grep -C <n> "<pattern>" <file>

Shows n lines either side.

Link
<command> | grep "<pattern>"

Filters the output of another command.

Link