Docs / Linux Basics / How to Use grep to Search File Contents

How to Use grep to Search File Contents

By Admin · Feb 25, 2026 · Updated Apr 24, 2026 · 231 views · 1 min read

grep searches for text patterns within files. It's one of the most powerful Linux tools.

Basic Search

grep "search term" filename

Useful Options

# Case-insensitive
grep -i "error" /var/log/syslog

# Recursive (search directories)
grep -r "TODO" /var/www/

# Show line numbers
grep -n "function" script.py

# Show context (lines before/after)
grep -C 3 "error" logfile

# Invert match (lines NOT matching)
grep -v "debug" logfile

# Count matches
grep -c "error" logfile

Regular Expressions

# Lines starting with "Error"
grep "^Error" logfile

# Lines ending with a number
grep "[0-9]$" logfile

# IP addresses (basic)
grep -E "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" logfile

Was this article helpful?