grep Command on Linux: Search Files, Logs and Pipelines (with Regex Basics)

grep command linux - custom-grep-featured.png

grep is how you answer “where does this string appear?” in configs, application logs, or the output of another command.
It is one of the most searched Linux topics because almost every troubleshooting session starts with a text search.

This guide covers daily flags, safe recursive searches, and piping from journalctl or
Nginx logs. For huge git trees, consider rg (ripgrep) with the same mental model.

Three Ways to Use grep

Search one file, walk a directory tree with -r, or filter stdout from a pipe. All three share the same pattern syntax.

bashexamples
grep 'error' /var/log/nginx/error.log
grep -r 'listen 443' /etc/nginx/
journalctl -u app --since today | grep -i timeout
grep modes
file, recursive, pipe

Literal Text vs Regex

Default grep treats some characters as regex metacharacters. Use -F for fixed strings; -E for extended regex when you need alternation.

bashpatterns
grep -F 'price($)' data.txt
grep -E 'error|warn|fatal' app.log
TipWhen searching for dots or brackets from log lines, -F avoids surprises.
Pattern types
literal, -E, -F

Flags You Will Use Every Day

-i ignores case; -n prints line numbers; -v inverts the match (lines that do not match).

bashdaily combo
grep -in 'connection refused' /var/log/syslog
grep -v '^#' /etc/ssh/sshd_config
Common flags
-i, -n, -v

Show Context Around a Match

When a single line is not enough, -A, -B, and -C print neighbouring lines so you see stack traces or config blocks.

bashcontext
grep -C3 'Exception' application.log | head -40
Context
-A -B -C

Recursive Search With Filters

Limit noise with --include and --exclude-dir so you do not scan node_modules or vendor trees by accident.

bashfocused tree search
grep -r --include='*.conf' 'ssl_certificate' /etc/nginx/
grep -r --exclude-dir='.git' 'TODO' ~/project/
grep -r
include and exclude

Pipelines and Counting

grep shines after another command. Remember ps aux | grep nginx also matches the grep process itself — use grep -v grep or pgrep.

bashcounts
grep -c ' 404 ' /var/log/nginx/access.log
zgrep -c 'OutOfMemory' /var/log/app.log.*.gz
Pipes
filter and count

When grep Gets Slow

On multi-gigabyte logs, narrow with journalctl time filters first. On large codebases, rg respects .gitignore by default.

bashcompressed logs
zgrep 'panic' /var/log/kern.log.1.gz
Performance
narrow, then search

Quick Reference

  • grep -rn recursive + line numbers; -i case-insensitive
  • -F fixed string; -E for | alternation
  • Pipe wisely; use zgrep on rotated .gz logs

Related tutorials

Diagrams are original illustrations by Gnome IT Solutions. Tutorial text © Gnome IT Solutions.