grep Command: Practical Examples & Usage Guide
Master grep with practical examples for developers. Search text patterns efficiently in files, directories, and codebases with regex support.
Dai Aoki
CEO at init, Inc. / CTO at US & JP startups / Creator of WebTerm
Try grep in your browser
Practice grep commands interactively without installing anything.
Quick Reference
Basic
grep "pattern" fileSearch in filegrep -r "pattern" dir/Recursive searchgrep -i "pattern" fileCase-insensitiveOutput
-nShow line numbers-cCount matches-lShow only filenamesContext
-A 3Show 3 lines after-B 3Show 3 lines before-C 3Show 3 lines aroundFiltering
-vInvert match-wMatch whole words-EExtended regexFile Selection
--include="*.js"Only search .js files--exclude-dir=node_modulesSkip directory-ISkip binary filesCommon Combos
grep -rn "TODO" .Find TODOs with line #grep -rl "pattern" .List files with matchgrep -E "a|b" fileMatch a OR bDownloadable Image Preview
Basic Usage
grep (Global Regular Expression Print) searches for patterns in files and outputs matching lines. The basic syntax is straightforward:
# Basic syntax
grep "pattern" filename
# Search in multiple files
grep "pattern" file1.txt file2.txt
# Search from stdin (pipe)
cat file.txt | grep "pattern"
echo "Hello World" | grep "World"Essential Options
These are the most frequently used grep options that every developer should know:
| Option | Description | Example |
|---|---|---|
| -i | Case-insensitive search | grep -i "error" log.txt |
| -r, -R | Recursive search in directories | grep -r "TODO" ./src/ |
| -n | Show line numbers | grep -n "function" app.js |
| -v | Invert match (show non-matching lines) | grep -v "#" config.txt |
| -c | Count matching lines | grep -c "error" log.txt |
| -l | Show only filenames with matches | grep -l "import" *.js |
| -L | Show only filenames without matches | grep -L "test" *.js |
| -w | Match whole words only | grep -w "error" log.txt |
| -x | Match entire line | grep -x "OK" status.txt |
| -E | Extended regex (same as egrep) | grep -E "err|warn" log.txt |
| -F | Fixed strings (no regex, faster) | grep -F "[ERROR]" log.txt |
| -P | Perl-compatible regex (PCRE) | grep -P "\d{3}-\d{4}" file.txt |
# Case-insensitive search
grep -i "error" application.log
# Recursive search with line numbers
grep -rn "TODO" ./src/
# Match whole words only (won't match "errors" or "error_code")
grep -w "error" logfile.txt
# Count matches in each file
grep -c "import" *.jsOutput Control Options
Control what grep outputs and how context is displayed:
| Option | Description | Example |
|---|---|---|
| -A NUM | Show NUM lines after match | grep -A 3 "error" log.txt |
| -B NUM | Show NUM lines before match | grep -B 2 "error" log.txt |
| -C NUM | Show NUM lines of context (before & after) | grep -C 2 "error" log.txt |
| -o | Show only matching part of line | grep -o "[0-9]+" data.txt |
| -H | Always print filename with match | grep -H "error" log.txt |
| -h | Never print filename | grep -h "error" *.log |
| --color | Highlight matches in color | grep --color=auto "error" log.txt |
| -q | Quiet mode (exit status only) | grep -q "error" log.txt && echo "Found" |
# Show 3 lines before and 2 lines after each match
grep -B 3 -A 2 "Exception" error.log
# Show 5 lines of context around each match
grep -C 5 "CRITICAL" application.log
# Extract only the matching portions (useful with regex)
grep -oE "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" contacts.txt
# Quiet mode for scripts (check if pattern exists)
if grep -q "error" logfile.txt; then
echo "Errors found!"
fiFile Selection Options
Control which files grep searches:
| Option | Description | Example |
|---|---|---|
| --include | Only search files matching pattern | grep -r --include="*.js" "func" |
| --exclude | Skip files matching pattern | grep -r --exclude="*.min.js" "func" |
| --exclude-dir | Skip directories matching pattern | grep -r --exclude-dir=node_modules "func" |
| --include-dir | Only search in matching directories | grep -r --include-dir=src "func" |
| -I | Skip binary files | grep -rI "pattern" . |
# Search only in JavaScript files
grep -r --include="*.js" "useState" ./src/
# Search in multiple file types
grep -r --include="*.ts" --include="*.tsx" "interface" ./src/
# Exclude node_modules and build directories
grep -r --exclude-dir=node_modules --exclude-dir=dist "TODO" .
# Skip minified and map files
grep -r --exclude="*.min.js" --exclude="*.map" "function" ./src/git grep which automatically respects .gitignore and only searches tracked files.Regular Expressions
grep supports powerful regular expressions for pattern matching. Use -E for extended regex or -P for Perl-compatible regex.
POSIX Character Classes
| Class | Equivalent | Matches |
|---|---|---|
| [[:alnum:]] | [a-zA-Z0-9] | Alphanumeric characters |
| [[:alpha:]] | [a-zA-Z] | Alphabetic characters |
| [[:digit:]] | [0-9] | Digits |
| [[:lower:]] | [a-z] | Lowercase letters |
| [[:upper:]] | [A-Z] | Uppercase letters |
| [[:space:]] | [ \t\n\r\f\v] | Whitespace characters |
| [[:punct:]] | Punctuation | Punctuation characters |
| [[:xdigit:]] | [0-9a-fA-F] | Hexadecimal digits |
Quantifiers
| Quantifier | Description | Example |
|---|---|---|
| * | Zero or more | grep "ab*c" (ac, abc, abbc...) |
| + | One or more (extended) | grep -E "ab+c" (abc, abbc...) |
| ? | Zero or one (extended) | grep -E "colou?r" (color, colour) |
| {n} | Exactly n times | grep -E "[0-9]{4}" (4 digits) |
| {n,} | n or more times | grep -E "a{2,}" (aa, aaa...) |
| {n,m} | Between n and m times | grep -E "[0-9]{2,4}" (2-4 digits) |
Anchors & Boundaries
| Anchor | Description | Example |
|---|---|---|
| ^ | Start of line | grep "^Error" (lines starting with Error) |
| $ | End of line | grep "done$" (lines ending with done) |
| \b | Word boundary | grep "\bword\b" (whole word) |
| \B | Non-word boundary | grep "\Bword" (word within word) |
# Lines starting with "import"
grep "^import" app.js
# Lines ending with semicolon
grep ";$" code.js
# Match IP addresses
grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}" access.log
# Match email addresses
grep -E "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" contacts.txt
# Match URLs
grep -E "https?://[a-zA-Z0-9./?=_-]+" links.txt
# Match phone numbers (US format)
grep -E "\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}" contacts.txtPractical Examples for Developers
Searching in a Codebase
# Find all TODO comments in JavaScript/TypeScript files
grep -rn --include="*.js" --include="*.ts" --include="*.tsx" "TODO" ./src/
# Find function definitions
grep -rn "function.*(" --include="*.js" ./src/
# Find React component definitions
grep -rn "const.*=.*:.*FC\|function.*Component" --include="*.tsx" ./src/
# Find all imports from a specific package
grep -rn "from 'react'" --include="*.tsx" ./src/
# Find unused exports (files that export but aren't imported anywhere)
for file in $(grep -rl "export " --include="*.ts" ./src/); do
name=$(basename "$file" .ts)
if ! grep -rq "from '.*$name'" --include="*.ts" ./src/; then
echo "Potentially unused: $file"
fi
done
# Find console.log statements (to remove before production)
grep -rn "console\.log" --include="*.js" --include="*.ts" ./src/Log File Analysis
# Find all errors in log files
grep -i "error\|exception\|fail" application.log
# Find errors with timestamp context
grep -B 1 -A 2 "ERROR" application.log
# Count errors per day
grep -o "^[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}.*ERROR" app.log | cut -d' ' -f1 | sort | uniq -c
# Find slow API requests (>1000ms)
grep -E "duration=[0-9]{4,}ms" access.log
# Extract unique IP addresses from access logs
grep -oE "([0-9]{1,3}\.){3}[0-9]{1,3}" access.log | sort -u
# Find 5xx errors
grep -E "HTTP/[0-9.]+ 5[0-9]{2}" access.log
# Find requests by user agent
grep -i "curl\|wget\|python-requests" access.logConfiguration File Search
# Find all environment variable references
grep -rh "process\.env\." --include="*.js" --include="*.ts" ./src/ | sort -u
# Find hardcoded credentials (security audit)
grep -rniE "password\s*=\s*['"][^'"]+['"]" --include="*.js" --include="*.env" .
# Find API endpoints
grep -rn "api/\|/api/" --include="*.js" --include="*.ts" ./src/
# Find all URLs in config files
grep -hE "https?://[^"'\s]+" *.json *.yaml *.yml 2>/dev/null
# Find deprecated features
grep -rn "@deprecated" --include="*.ts" ./src/Advanced Pattern Matching
# Search for multiple patterns (OR)
grep -E "error|warning|critical" log.txt
# Search for patterns that must all appear (AND - same line)
grep "error.*database\|database.*error" log.txt
# Search for pattern NOT followed by another pattern
grep "error" log.txt | grep -v "handled"
# Find lines with exactly 3 fields (tab-separated)
grep -E "^[^\t]+\t[^\t]+\t[^\t]+$" data.tsv
# Find duplicate consecutive words
grep -E "\b(\w+)\s+\1\b" document.txt
# Find files containing pattern A but not pattern B
grep -l "import React" --include="*.tsx" ./src/ | xargs grep -L "useState"
# Combine grep with find for complex searches
find . -name "*.js" -mtime -7 -exec grep -l "TODO" {} \;--exclude-dir to skip node_modules, .git, and build directories to improve performance.Frequently Asked Questions
How do I ignore case when searching with grep?
Use the -i flag: grep -i "pattern" file.txt. This makes the search case-insensitive, matching "Error", "ERROR", "error", etc.
How do I search recursively in directories with grep?
Use the -r or -R flag: grep -r "pattern" /path/to/directory. The -R flag also follows symbolic links, while -r does not.
How do I exclude directories when using grep recursively?
Use the --exclude-dir option: grep -r --exclude-dir=node_modules --exclude-dir=.git "pattern" . You can specify multiple directories to exclude.
How do I search for multiple patterns with grep?
Use the -e flag for each pattern: grep -e "pattern1" -e "pattern2" file.txt. Alternatively, use extended regex with -E: grep -E "pattern1|pattern2" file.txt
How do I show line numbers in grep output?
Use the -n flag: grep -n "pattern" file.txt. This displays the line number before each matching line.
How do I show only filenames that match with grep?
Use the -l flag: grep -l "pattern" *.txt. This outputs only the names of files containing matches, not the matching lines themselves.
How do I invert the match to show non-matching lines?
Use the -v flag: grep -v "pattern" file.txt. This shows all lines that do NOT match the pattern.
What is the difference between grep, egrep, and fgrep?
grep uses basic regex, egrep (grep -E) uses extended regex with support for +, ?, |, and (). fgrep (grep -F) treats patterns as fixed strings, which is faster for literal text searches.
Summary
grep is an essential tool for searching through files and text streams. Master these patterns and options to efficiently search through codebases, analyze logs, and automate text processing tasks.
Quick Reference
grep -i- Case insensitivegrep -r- Recursive searchgrep -n- Show line numbersgrep -v- Invert matchgrep -l- Files with matches onlygrep -c- Count matchesgrep -E- Extended regexgrep -o- Show only matching partgrep -A/-B/-C- Context linesgrep --include/--exclude- File filtering
Official Documentation
For authoritative information, refer to the official documentation:
Practice grep interactively
Try these grep commands in our browser-based terminal. No installation required.