grep and Regular Expressions
Searching file content with grep, egrep, and basic regex patterns
Skills taught: linux.grep, linux.regex-basics, linux.grep-flags
grep essentials
# Basic: search for a pattern in a file
grep "ERROR" server.log # lines containing ERROR
grep "error" server.log # case-sensitive
grep -i "error" server.log # -i: case-insensitive
grep -n "ERROR" server.log # -n: show line numbers
grep -c "ERROR" server.log # -c: count matching lines
grep -v "DEBUG" server.log # -v: invert (lines NOT matching)
grep -l "TODO" *.js # -l: only print filenames
# Search recursively in a directory
grep -r "console.log" ./src/ # -r: recursive
grep -rn "TODO" ./src/ # with line numbers
grep -ri "password" ./config/ # recursive + case-insensitive
# Context lines
grep -A 3 "ERROR" server.log # 3 lines After match
grep -B 2 "ERROR" server.log # 2 lines Before match
grep -C 5 "ERROR" server.log # 5 lines Context (before + after)
# Exact word match
grep -w "log" server.log # 'log' not 'logging' or 'changelog'
Basic regular expressions
# . matches any single character
grep "e.g" file.txt # matches 'egg', 'e-g', 'e g'
# ^ matches start of line, $ matches end of line
grep "^Error" file.txt # lines starting with 'Error'
grep "done$" file.txt # lines ending with 'done'
grep "^$" file.txt # empty lines
# * matches zero or more of the preceding char
grep "colou*r" file.txt # matches 'color', 'colour', 'colouur'
# [] matches any character in the set
grep "[0-9]" file.txt # lines with at least one digit
grep "[A-Z]" file.txt # lines with uppercase letters
grep "[^a-z]" file.txt # lines with non-lowercase chars
# Extended regex with -E (or use egrep)
grep -E "error|warning|fatal" server.log # OR
grep -E "^[0-9]{4}-" timestamps.txt # starts with 4 digits + dash
grep -E "https?://" urls.txt # http or https
grep -E "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b" text.txt # email
Tip: Use grep -E for extended regex (alternation |, +, ?, {n}) and grep -P for Perl-compatible regex (\d, \w, \s). Quote your patterns in single quotes to prevent the shell from interpreting special characters.
Frequently Asked Questions
What is the difference between grep, egrep, and fgrep?
grep uses basic regex. egrep (same as grep -E) uses extended regex with |, +, ?, {}. fgrep (same as grep -F) treats the pattern as a literal string (no regex) — faster when searching for fixed strings like file paths or error codes. In modern scripts, prefer grep -E and grep -F flags over the egrep/fgrep aliases.