grep & regular expressions
Matching lines, and the difference between basic and extended regex.
Before you start
grep searches text for lines that match a pattern and prints them. That's the entire job. But because it works on any stream — a file, the output of another command — it turns into one of the most-used tools you'll ever meet.
The pattern can be a literal string (grep error log.txt) or a **regular expression** — a small language for describing shapes of text (grep -E "^[0-9]+ ERROR").
This lesson runs grep on a log file, shows which lines are kept and which are dropped, then covers the flags you'll actually use daily: -i, -n, -v, and -E.
server.log
grep scans line by line| Row | server.log |
|---|---|
| 1 | 2024-01-15 INFO startup complete |
| 2 | 2024-01-15 ERROR connection timeout |
| 3 | 2024-01-15 INFO request handled |
| 4 | 2024-01-15 WARN high latency |
| 5 | 2024-01-15 ERROR disk full |
| 6 | 2024-01-16 INFO recovered |
"error" does not match "ERROR". grep is case-sensitive by default.
Step 1 of 6. grep prints lines containing the pattern. `grep "error" server.log` reads every line of the file and prints only those containing the string "error". Case matters — "ERROR" would not match. grep does not modify the file. It reads, filters, and writes to stdout. The original file is untouched.
Step 01 / 06
grep prints lines containing the pattern
grep "error" server.log reads every line of the file and prints only those containing the string "error". Case matters — "ERROR" would not match.
grep does not modify the file. It reads, filters, and writes to stdout. The original file is untouched.
# Basic grep: lines containing "error"grep "error" server.log# Case-insensitivegrep -i "error" server.log# Line numbersgrep -n "error" server.log# Invert: lines NOT containing "error"grep -v "error" server.log# Extended regex: one or more digitsgrep -E "[0-9]+" server.log# Anchors: lines starting with "2024"grep "^2024" server.log# Pipe: filter output of another commandps aux | grep nginx