Skip to content

Grep Command Guide

Mattscreative edited this page Dec 5, 2025 · 4 revisions

Grep Command Troubleshooting for Beginners

Table of Contents

  1. 📝 What is grep?
  2. ⚡ Basic Commands
  3. 🔍 Output Options
  4. 🔎 Context Options
  1. 📈 Advanced Options
  1. 🔗 Using Grep with Pipes
  1. 💡 Common Troubleshooting Scenarios
  1. ⌨️ Quick Reference
  1. ⚠️ Important Tips
  2. Summary

📝 What is grep?

  • grep (Global Regular Expression Print) searches for text patterns in files
  • One of the most essential Linux commands
  • Used for searching, filtering, and extracting information
  • Works with files, command output, and pipes

What grep can do:

  • Search for text in files
  • Filter command output
  • Find patterns (exact text or regular expressions)
  • Count matches
  • Show context around matches
  • Search recursively in directories

Common uses:

  • Searching log files for errors
  • Filtering command output
  • Finding specific text in code
  • Extracting information from files

⚡ Basic Commands

Search in a File

grep "pattern" filename

What this does:

  • Searches for "pattern" in the file
  • Shows all lines containing the pattern
  • Case-sensitive by default

Example:

grep "error" logfile.txt

Shows all lines containing "error".


Search in Multiple Files

grep "pattern" file1.txt file2.txt

What this does:

  • Searches for pattern in multiple files
  • Shows filename with each match

Example:

grep "ERROR" *.log

Searches for "ERROR" in all .log files.


Search in All Files (Recursive)

grep -r "pattern" /path/to/directory

What this does:

  • Recursively searches all files in directory
  • Includes all subdirectories
  • Very useful for searching codebases

Example:

grep -r "function_name" /path/to/project

Case-Insensitive Search

grep -i "pattern" filename

What this does:

  • Searches case-insensitively
  • -i = ignore case
  • Finds "Error", "ERROR", "error", etc.

Example:

grep -i "error" logfile.txt

🔍 Output Options

Show Line Numbers

grep -n "pattern" filename

What this does:

  • Shows line number with each match
  • Very useful for locating matches in files

Example:

grep -n "error" logfile.txt

Output:

15:error: connection failed
42:error: timeout occurred

Show Filename with Matches

grep -H "pattern" filename

What this does:

  • Shows filename with each match
  • Useful when searching multiple files
  • -H is default when multiple files are searched

Example:

grep -H "error" *.log

Suppress Filename (Only Show Matches)

grep -h "pattern" file1 file2

What this does:

  • Suppresses filename in output
  • Only shows matching lines
  • Useful when you don't need to know which file

Show Only Filenames (No Match Text)

grep -l "pattern" *.txt

What this does:

  • Lists only filenames containing the pattern
  • Doesn't show the actual matches
  • Useful for finding which files contain the pattern

Example:

grep -l "TODO" *.md

Shows which .md files contain "TODO".


Invert Match (Show Non-Matching Lines)

grep -v "pattern" filename

What this does:

  • Shows lines that DON'T match the pattern
  • -v = invert match
  • Useful for filtering out unwanted lines

Example:

grep -v "^#" configfile

Shows all lines except those starting with # (comments).


🔎 Context Options

Show Lines Before Match

grep -B 3 "pattern" filename

What this does:

  • Shows 3 lines before each match
  • -B = before
  • Useful for understanding context

Example:

grep -B 5 "error" logfile.txt

Show Lines After Match

grep -A 3 "pattern" filename

What this does:

  • Shows 3 lines after each match
  • -A = after
  • Useful for seeing what happens after an error

Example:

grep -A 5 "error" logfile.txt

Show Lines Before and After

grep -C 3 "pattern" filename

What this does:

  • Shows 3 lines before AND after each match
  • -C = context
  • Best of both worlds

Example:

grep -C 5 "error" logfile.txt

Shows 5 lines before and after each error.


📈 Advanced Options

Count Matches

grep -c "pattern" filename

What this does:

  • Counts number of matching lines
  • -c = count
  • Doesn't show the actual matches, just the count

Example:

grep -c "error" logfile.txt

Output:

42

Means 42 lines contain "error".


Match Whole Words Only

grep -w "pattern" filename

What this does:

  • Matches only whole words
  • -w = word boundary
  • Prevents partial matches

Example:

grep -w "error" file.txt

Matches "error" but not "errors" or "terror".


Match Whole Lines Only

grep -x "pattern" filename

What this does:

  • Matches only if entire line matches pattern
  • -x = exact line match
  • Useful for exact matches

Limit Number of Matches

grep -m 10 "pattern" filename

What this does:

  • Stops after finding 10 matches
  • -m = max count
  • Useful for large files

Example:

grep -m 5 "error" huge_logfile.txt

Shows only first 5 errors.


🔗 Using Grep with Pipes

Filter Command Output

command | grep "pattern"

What this does:

  • Filters command output through grep
  • Shows only lines matching pattern
  • Very common pattern

Examples:

ps aux | grep nginx
systemctl status | grep failed
journalctl | grep error

Combine with Other Commands

grep "pattern" file.txt | wc -l

What this does:

  • Counts matching lines
  • Pipes grep output to wc -l
  • Alternative to grep -c

Example:

grep "error" logfile.txt | wc -l

💡 Common Troubleshooting Scenarios

Scenario 1: Find Errors in Log File

Problem: Need to find all errors in a log file.

Solution:

grep -i "error" logfile.txt

With line numbers:

grep -n -i "error" logfile.txt

With context:

grep -C 5 -i "error" logfile.txt

Scenario 2: Search Multiple Files

Problem: Need to search for text in multiple files.

Solution:

grep -r "pattern" /path/to/directory

Only in specific file types:

grep -r "pattern" --include="*.txt" /path

Scenario 3: Filter Out Comments

Problem: Need to see config file without comments.

Solution:

grep -v "^#" configfile

Removes lines starting with #.

Also remove empty lines:

grep -v "^#" configfile | grep -v "^$"

Scenario 4: Find IP Addresses

Problem: Need to extract IP addresses from a file.

Solution:

grep -E "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" file.txt

Uses extended regex (-E) for pattern matching.


Scenario 5: Count Occurrences

Problem: Need to count how many times a pattern appears.

Solution:

grep -c "pattern" file.txt

Or:

grep "pattern" file.txt | wc -l

Scenario 6: Find Files Containing Pattern

Problem: Need to know which files contain a pattern.

Solution:

grep -l "pattern" *.txt

Lists filenames only.


Scenario 7: Search with Context

Problem: Need to see what happened before/after an error.

Solution:

grep -C 10 "error" logfile.txt

Shows 10 lines before and after each error.


⌨️ Quick Reference

Basic Commands

grep "pattern" file              # Search in file
grep "pattern" file1 file2       # Multiple files
grep -r "pattern" /path          # Recursive search
grep -i "pattern" file           # Case-insensitive

Output Options

grep -n "pattern" file           # Show line numbers
grep -H "pattern" file            # Show filename
grep -l "pattern" *.txt          # Show filenames only
grep -v "pattern" file           # Invert match
grep -c "pattern" file           # Count matches

Context Options

grep -B 5 "pattern" file         # 5 lines before
grep -A 5 "pattern" file         # 5 lines after
grep -C 5 "pattern" file         # 5 lines before/after

Advanced Options

grep -w "pattern" file            # Whole words only
grep -x "pattern" file            # Whole lines only
grep -m 10 "pattern" file         # Limit to 10 matches

With Pipes

command | grep "pattern"          # Filter output
grep "pattern" file | wc -l       # Count matches

⚠️ Important Tips

  1. Use quotes around patterns with spaces or special characters
  2. Case sensitivity - use -i for case-insensitive search
  3. Regular expressions - use -E for extended regex
  4. Large files - use -m to limit matches
  5. Recursive search - use -r for directory searches
  6. Context - use -C to see surrounding lines

Summary

This guide covered:

  1. Basic Usage:
  • Searching in files
  • Multiple files
  • Recursive search
  1. Output Options:
  • Line numbers
  • Filenames
  • Invert match
  • Count matches
  1. Context Options:
  • Lines before/after
  • Context around matches
  1. Advanced Options:
  • Whole words/lines
  • Limit matches
  • Extended regex
  1. Using with Pipes:
  • Filtering command output
  • Combining commands
  1. Troubleshooting Scenarios:
  • Finding errors
  • Searching multiple files
  • Filtering output

Next Steps:

  • Practice with log files
  • Combine with other commands (find, ps, etc.)
  • Learn regular expressions for advanced patterns
  • Master context options for debugging

For finding files, see the Find Command Guide. For process management, see the PS Process Management Guide.

Clone this wiki locally