How-to

The grep Command with Examples

grep prints lines that match a pattern. It is the first tool for reading logs, checking configs and searching code on any server.

What is the basic form?

grep 'server_name' /etc/nginx/sites-enabled/shop.conf

grep pattern file... prints each line of the files that contains the pattern. Without a file, grep reads standard input, which is why it appears at the end of so many pipelines: journalctl -u php8.3-fpm | grep -i warning. Quote patterns so the shell does not expand *, $ or spaces first.

Which options do I use every day?

OptionEffect
-iIgnore case
-wMatch whole words only
-nShow line numbers
-r / -RSearch folders recursively; -R also follows symlinks
-l / -LList files that match / do not match
-A 3, -B 3, -C 3Lines after, before, or around each match
-oPrint only the matching part
-vInvert: lines that do not match
-cCount matching lines
-qQuiet: exit status only, for scripts
grep -rn --color=auto 'upload_max_filesize' /etc/php/
grep -C 2 'Out of memory' /var/log/syslog

What are the regex flavors?

grep supports three:

  • Basic (default): ., *, ^, $, [ ] work directly; +, ?, |, { } and groups need backslashes.
  • Extended (-E): those operators work without backslashes. Most people use this.
  • Perl-compatible (-P): adds \d, lookarounds and \K, available in GNU grep on Linux.
grep -E '^(GET|POST) /api/v[12]/' requests.log
grep -P '(?<=user=)\w+' audit.log
grep -oE '\b([0-9]{1,3}\.){3}[0-9]{1,3}\b' /var/log/nginx/error.log | sort -u

The last line extracts unique IPv4 addresses from a log, a handy first step when investigating abusive clients. On FreeBSD, the base grep supports -E but not -P; install GNU grep as ggrep if you need Perl regex.

How do I use grep in scripts?

grep's exit status is the useful output there: 0 when something matched, 1 when nothing did, 2 on errors.

if grep -qx 'PasswordAuthentication no' /etc/ssh/sshd_config.d/*.conf; then echo keys-only; fi
grep -q '^deploy:' /etc/passwd || useradd -m -s /bin/bash deploy

-x requires the whole line to match, avoiding false hits on commented or longer lines. Checks like these make provisioning scripts safe to run twice.

How do I search compressed and rotated logs?

zgrep handles .gz files with the same options, and xzgrep, bzgrep and zstdgrep cover the other formats. To search current and rotated logs in one go: zgrep -h 'Accepted publickey' /var/log/auth.log*. On systems logging only to the journal, use journalctl -g instead, which searches inside the journal with a regex.

How do I make grep faster?

  • -F for fixed strings skips the regex engine.
  • LC_ALL=C avoids slow multibyte handling on ASCII data.
  • -m 1 stops after the first match when you only need to know one exists.
  • For huge code trees, ripgrep (rg) searches in parallel and respects ignore files.

Counting results is covered in Count matches with grep, excluding noise in Exclude with grep, and searching for several patterns in Grep for multiple strings. To edit what you find rather than print it, see The sed command.

How do I highlight matches in color?

--color=auto colors the matched text when output goes to a terminal; most distributions set it through an alias already. GREP_COLORS='mt=01;33' changes the color, which helps on dark terminals. Use --color=always only when piping into less -R, since raw color codes confuse other tools.

How do I show the file name with every match?

With one file, grep omits names; with several, it adds them. Force either behavior with -H or -h. grep -Hn 'listen' /etc/nginx/nginx.conf prints file:line:text, a format editors such as Vim can open directly at the right line.

One last habit: when a search returns nothing, check the obvious first. Is the file compressed, is the case different, did the log rotate an hour ago? Most "grep found nothing" moments end with zgrep, -i or the previous log file.

Keep Reading

Count matches with grep

Count matching lines, every match, matches per file and per value with grep -c, -o and a few pipes, plus common counting traps.

Open

Exclude with grep

Leave things out of grep results: invert matches, skip files and folders by pattern, ignore binaries and comments, and filter noisy log lines.

Open

Grep for multiple strings

Match any of several patterns, all of them on one line, whole words from a list or strings in a set order, with grep and small pipelines.

Open

The sed command

Edit text streams and files with sed: substitutions, in-place edits with backups, line addresses, extended regex, multiple commands and GNU versus BSD.

Open

FAQ

Quick Answers

Add -i, for example grep -i error app.log.

Use grep -r pattern folder, adding -n for line numbers.

-E enables extended regex, where +, ?, | and groups work without backslashes.

Use -A for after, -B for before or -C for both, followed by a number of lines.

Use grep -q and test its exit status: 0 means a match was found.