Grep Command in Linux with Examples + Cheat Sheet

Share

On Linux systems, searching for specific text in files is something you’ll do often. The grep command is the ultimate tool for that.

Whether you want to quickly find an error in a log file, search code for functions, or filter outputs in scripts, grep makes it efficient.

While I’m using Ubuntu for this guide, everything here works the same on Linux Mint, Pop!_OS, Fedora, Debian, and most popular Linux distros.

You can also download a free Grep command cheat sheet below for offline reference to keep handy, while you do that, don’t hesitate to contact us or leave a comment below.

How to Use Grep Command in Linux

Basic Syntax

grep [options] pattern [file]

Example: Search for the word “error” in a log file

grep "error" /var/log/syslog

Common Grep Command Examples

Search for Exact Word in a File

grep "database" config.txt
  • Before Running: You have a file named config.txt and you want to locate the word “database”.
  • After Running: Lines containing “database” will be displayed in the terminal.

Search Recursively in a Directory

grep -r "function" ~/Projects/
  • Use Case: Find all files under Projects/ containing the word “function” (useful for code audits).

Case-Insensitive Search

grep -i "Ubuntu" README.md

Display Line Numbers with Matches

grep -n "server" /etc/nginx/nginx.conf

Show Only Matching Word (No Full Line)

grep -o "root" /etc/passwd

Search for Multiple Patterns

grep -E "error|failed|critical" /var/log/syslog

Invert Match (Show Lines That Do Not Contain Pattern)

grep -v "#" config.txt

Useful Grep Options

Option Description
-r Recursively search directories.
-i Ignore case distinctions.
-n Show line numbers of matching lines.
-o Show only the matching part of the line.
-v Invert match: select non-matching lines.
-E Use Extended Regular Expressions.
-l List only filenames with matches.
--color Highlight matching text in output.

Advanced Grep Examples

Show Lines Before and After Match (Context)

grep -C 3 "error" /var/log/syslog
  • Shows 3 lines before and after each match.

Count Number of Matches

grep -c "404" access.log

Search Inside Compressed Files

zgrep "keyword" archive.log.gz

Highlight Matches in Color

grep --color=always "main" *.c

Tips & Best Practices

  1. Always quote your search pattern to avoid shell misinterpretation.
  2. Use recursive (-r) with caution on large directories to avoid performance issues.
  3. Combine grep with other commands using pipes (|) for powerful data filtering.

Want to learn more Linux commands? Check out:

Each command post on our site comes with a FREE cheat sheet for you to download.