Searching text with grep

grep filters lines of text, keeping only those that match a pattern.

Syntaxgrep [options] pattern [file...]

grep searches text for lines matching a pattern and prints them. It reads from files, or from a pipe.

The most useful options

  • -i — ignore case.
  • -r — search recursively through a directory.
  • -n — show line numbers.
  • -v — invert: show lines that do not match.
  • -c — count matching lines instead of printing them.
  • -E — use extended regular expressions.

Patterns can be plain text or full regular expressions, making grep extremely flexible.

Example

Example · bash
# Find a word in a file
grep "timeout" config.yaml

# Case-insensitive, with line numbers
grep -in "error" app.log

# Search a whole project recursively
grep -rn "TODO" ./src

# Lines that do NOT contain 'debug'
grep -v "debug" app.log

When to use it

  • A developer uses 'grep -rn "TODO" ./src/' to find all TODO comments across a codebase before a release.
  • A sysadmin runs 'grep -i "error" /var/log/syslog' to spot error messages regardless of capitalisation.
  • A security analyst uses 'grep -E "^(FAILED|Invalid)" /var/log/auth.log' to extract failed authentication events.

More examples

Basic search and case-insensitive

Shows basic grep usage, the -i flag for case-insensitive matching, and -n to include line numbers.

Example · bash
# Search for exact word in a file
grep 'error' /var/log/syslog

# Case-insensitive search
grep -i 'ERROR' /var/log/syslog

# Show line numbers
grep -n 'error' /var/log/syslog

Recursive search in directory

Uses -r to search all files recursively, -n for line numbers, and -C for surrounding context lines.

Example · bash
# Search all .py files for a function name
grep -rn 'def authenticate' ./src/

# Search and show 2 lines of context
grep -rn -C 2 'database_url' ./config/

Extended regex with grep -E

Uses -E for extended regular expressions to match alternatives and extract IP addresses with -o (only matching).

Example · bash
# Match lines starting with FAILED or Invalid
grep -E '^(FAILED|Invalid)' /var/log/auth.log

# Extract IPv4 addresses
grep -oE '[0-9]{1,3}(\.[0-9]{1,3}){3}' access.log | sort -u

Discussion

  • Be the first to comment on this lesson.