grep
MASTERY

// Find. Match. Extract.

PATTERNS ARE POWER.

In a world of terabytes of text logs, configuration files, and code—grep is your flashlight. It finds exactly what you need in seconds.

KNOW YOUR TOOLS.

Master grep and you'll navigate any Linux system like a pro. Searching logs, finding config values, filtering output—all become effortless.

BEGIN YOUR JOURNEY

// Your Training Path

Click a lesson to begin

LESSON 01

Introduction to grep

What is grep? Basic syntax and usage.

Beginner
LESSON 02

Basic Pattern Matching

Search for simple strings and words.

Beginner
LESSON 03

Regular Expressions

Use regex metacharacters for powerful matching.

Beginner
LESSON 04

grep Options

-i, -v, -r, -n, -c and more.

Beginner
LESSON 05

Extended grep

egrep and grep -E for extended regex.

Intermediate
LESSON 06

Fixed Strings

grep -F for literal matching (fgrep).

Intermediate
LESSON 07

Context Lines

Show lines before, after, or around matches.

Intermediate
LESSON 08

Recursive Search

Search directories and subdirectories.

Intermediate
LESSON 09

Output Control

Quiet mode, count, only match.

Intermediate
LESSON 10

Combining with Pipes

Chain grep with other commands.

Intermediate
LESSON 11

grep in Scripts

Use grep in bash scripts for automation.

Advanced
LESSON 12

Advanced Patterns

Word boundaries, anchors, and complex regex.

Advanced

// Lesson 01: Introduction to grep

×

What is grep?

grep (Global Regular Expression Print) searches input files for lines containing a match to a specified pattern. It's one of the most useful commands on Linux.

Basic Syntax

grep [OPTIONS] PATTERN [FILE...]

Simple Example

# Search for 'error' in a log file
grep error /var/log/syslog

# Search in multiple files
grep "failed login" /var/log/auth.log /var/log/secure

Why grep Matters

  • Speed: Search millions of lines in seconds
  • Precision: Find exact patterns in vast amounts of text
  • Flexibility: Combine with regex for complex searches
  • Ubiquity: Available on every Linux system

Quiz

1. What does grep stand for?

Show Answers
  1. Global Regular Expression Print

// Lesson 02: Basic Pattern Matching

×

Simple String Search

# Search for a word in a file
grep root /etc/passwd

# Search in stdin
echo "The quick brown fox" | grep quick

Case-Insensitive Search

# The -i flag makes search case-insensitive
grep -i error /var/log/syslog

Match Whole Words

# Only match 'cat' as a whole word
grep -w cat file.txt

# Without -w, would also match 'cat' in 'category'

Quiz

1. Which flag makes grep case-insensitive?

Show Answers
  1. -i

// Lesson 03: Regular Expressions

×

Basic Regex Metacharacters

.  - Match any single character
^  - Match at beginning of line
$  - Match at end of line
*  - Match zero or more of preceding
[] - Match any character in brackets

Examples

# Lines starting with 'error'
grep ^error /var/log/syslog

# Lines ending with '.conf'
grep '\.conf$' /var/log/app.log

# 'warn' or 'error'
grep 'warn|error' /var/log/syslog

# Lines with a number
grep '[0-9]' file.txt

Escape Special Characters

# Search for a literal dot
grep '\.' file.txt

# Or use -F for fixed strings
grep -F 'example.com' file.txt

Quiz

1. What does ^ match?

Show Answers
  1. Beginning of line (anchor)

// Lesson 04: grep Options

×

Common Options

-i  Case insensitive
-v  Invert match (lines NOT matching)
-r  Recursive search
-n  Show line numbers
-c  Count matching lines only
-l  Show only filenames with matches
--color=auto  Highlight matches

Examples

# Show line numbers
grep -n " Port " /etc/ssh/sshd_config

# Count occurrences
grep -c "error" /var/log/syslog

# Invert match (lines WITHOUT 'error')
grep -v "error" /var/log/syslog

# Only show filenames
grep -l "configuration" /etc/*

Quiz

1. Which flag shows line numbers?

Show Answers
  1. -n

// Lesson 05: Extended grep (grep -E)

×

Extended Regex

Extended regex (ERE) doesn't require escaping special characters.

# Use -E or egrep
grep -E 'error|warning|critical' /var/log/syslog
egrep 'error|warning|critical' /var/log/syslog

Extended Metacharacters

+  One or more of preceding
?  Zero or one of preceding
() Grouping
{a,b} Between a and b repetitions

Examples

# One or more digits
grep -E '[0-9]+' file.txt

# Optional character
grep -E 'colou?r' file.txt  # matches color or colour

# IP address pattern
grep -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' access.log

Quiz

1. In extended regex, what does + mean?

Show Answers
  1. One or more of the preceding character

// Lesson 06: Fixed Strings (grep -F)

×

When to Use -F

Use grep -F (or fgrep) when you need to search for literal strings, not regex patterns. No escaping needed.

Examples

# Search for literal string (no regex)
grep -F 'example.com' access.log

# With fgrep (same as grep -F)
fgrep '127.0.0.1' /etc/hosts

# Search for a phrase with special chars
grep -F 'error.code = 500' app.log

Why Not Escape?

# Without -F, you must escape dots
grep 'error\.log' app.log

# With -F, no escaping needed
grep -F 'error.log' app.log

Quiz

1. When should you use grep -F?

Show Answers
  1. When searching for literal strings (not regex)

// Lesson 07: Context Lines

×

Show Lines Around Match

# Show 3 lines after match (default)
grep -A 3 "error" app.log

# Show 3 lines before match
grep -B 3 "error" app.log

# Show 2 lines before AND after
grep -C 2 "error" app.log

Examples

# Find error with context in logs
grep -C 5 "CRITICAL" syslog.log

# Before context for debugging
grep -B 10 "Segmentation fault" dmesg

Quiz

1. Which flag shows context lines around match?

Show Answers
  1. -C (context)

// Lesson 08: Recursive Search

×

Search Directories

# Recursive search in directory
grep -r "function" /var/www/html/

# Don't show line numbers with recursive
grep -rl "config" /etc/

# Include only certain files
grep -r --include="*.js" "api" /var/www/

Useful Recursive Options

--include=PATTERN  Only match files matching PATTERN
--exclude=PATTERN  Skip files matching PATTERN
--exclude-dir=DIR   Skip directories matching DIR

Examples

# Search only PHP files
grep -r --include="*.php" "mysql_connect" /var/www/

# Exclude log files
grep -r --exclude="*.log" "TODO" /project/

# Exclude node_modules
grep -r --exclude-dir=node_modules "export" /project/

Quiz

1. Which option limits search to specific files?

Show Answers
  1. --include=PATTERN

// Lesson 09: Output Control

×

Quiet Mode

# -q returns exit status only (for scripts)
grep -q "running" /var/run/app.pid && echo "App is running"

Show Only Matches

# -o shows only matched parts
echo "root:x:0:0:root:/root:/bin/bash" | grep -o 'root'

# Multiple matches on same line
echo "error error error" | grep -o 'error'

Quiet and Exit Codes

# grep returns:
# 0 = match found
# 1 = no match
# 2 = error

if grep -q "127.0.0.1" /etc/hosts; then
    echo "Localhost configured"
fi

Quiz

1. What does -o do in grep?

Show Answers
  1. Shows only the matched parts, not the whole line

// Lesson 10: Combining with Pipes

×

Power Combinations

# ps with grep (find processes)
ps aux | grep nginx

# Exclude the grep process itself
ps aux | grep nginx | grep -v grep

# dmesg with grep
dmesg | grep -i error

# Find largest files then grep
find /var/log -type f -exec ls -lh {} \; | grep error

Advanced Piping

# Chain multiple greps
cat access.log | grep "404" | grep -v "googlebot" | sort | uniq -c | sort -rn

# grep with awk
grep "error" app.log | awk '{print $1, $2, $NF}'

# Use in if statement
if cat /etc/os-release | grep -q "Ubuntu"; then
    echo "This is Ubuntu"
fi

Quiz

1. How do you exclude the grep process from results?

Show Answers
  1. grep -v grep

// Lesson 11: grep in Scripts

×

Script Examples

#!/bin/bash
# Check if service is running
if ps aux | grep -q "[a]pache2"; then
    echo "Apache is running"
else
    echo "Apache is not running"
fi

Log Analysis Script

#!/bin/bash
# Count errors by type
ERRORS=$(grep -c "ERROR" /var/log/app.log)
WARNINGS=$(grep -c "WARNING" /var/log/app.log)
CRITICAL=$(grep -c "CRITICAL" /var/log/app.log)

echo "Errors: $ERRORS"
echo "Warnings: $WARNINGS"  
echo "Critical: $CRITICAL"

Find and Replace Pattern

# Find files containing pattern and list them
for f in $(find . -type f -name "*.conf"); do
    if grep -q "Listen 80" "$f"; then
        echo "Port 80 found in: $f"
    fi
done

Quiz

1. What exit code does grep return when no match is found?

Show Answers
  1. 1 (zero means match found, 1 means no match)

// Lesson 12: Advanced Patterns

×

Word Boundaries

# \b matches word boundary
grep '\bcat\b' file.txt  # 'cat' only, not 'category'

# Also use -w (same effect)
grep -w 'cat' file.txt

Line Anchors

^  Beginning of line
$  End of line

# Empty lines
grep '^$' file.txt

# Lines with only whitespace
grep '^[[:space:]]*$' file.txt

Complex Examples

# Email pattern
grep -E '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}' file.txt

# IP address
grep -E '\b([0-9]{1,3}\.){3}[0-9]{1,3}\b' access.log

# Date formats
grep -E '[0-9]{4}-[0-9]{2}-[0-9]{2}' logfile

Congratulations!

You've mastered grep! You now understand:

  • Basic and extended regex
  • All important grep options
  • Context lines and output control
  • Recursive search
  • Script integration
  • Complex pattern matching

// Why grep

grep is the Swiss Army knife of text searching on Linux. Every sysadmin, developer, and power user relies on it daily.

Master grep and you'll find answers in seconds instead of scrolling through thousands of lines manually.

Find. Match. Extract. Automate.

// Tools & References

grep Man Page

Official documentation

man grep

regex101

Online regex tester

regex101.com

grep Tutorial

Linuxize grep guide

Linuxize

Regex Cheatsheet

Quick reference

QuickRef