Shell (Bash) Tutorial

Grep & Regular Expressions

Searching for patterns in files and command output

What is Grep?

grep (Global Regular Expression Print) is the standard tool for searching text in the shell. It searches through files (or input from a pipe) and prints every line that matches a specific pattern.
bash
grep "ERROR" system.log

Common Flags

FlagMeaningDescription
-iCase-InsensitiveIgnore capital letters
-vInvertShow lines that DON'T match
-rRecursiveSearch through all files in all subdirectories
-lListShow only the names of files that contain the match
-nNumbersShow the line numbers
-EExtendedEnable modern RegEx features (like `

Regular Expressions

Grep becomes truly powerful when you use Regular Expressions to describe the shape of the text you are looking for.
bash
# Find lines that start with 'root'
grep "^root" /etc/passwd

# Find lines that end with 'sh'
grep "sh$" /etc/passwd
Wait! Use grep -E (or egrep) to use the "Extended" syntax, which is much closer to what you find in Python or JavaScript.

Summary

TermDescription
grepStandard search tool
egrepGrep with Extended RegEx
^Matches the start of a line
$Matches the end of a line
.Matches any single character
*Matches 0 or more of the previous character
Best ForSearching logs, finding files, and filtering data
Logic"Textual pattern discovery"
SafetyGrep is extremely fast and safe for massive files
ModernTools like ripgrep (rg) are modern, faster alternatives
StandardAvailable on every Unix/Linux/Mac system
IdentityThe "Grep" name is so famous it became a verb ("Grep that log")