Terminal GuideTerminal Guide

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.

12 min readLast updated: January 19, 2025
Dai Aoki

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 file
grep -r "pattern" dir/Recursive search
grep -i "pattern" fileCase-insensitive

Output

-nShow line numbers
-cCount matches
-lShow only filenames

Context

-A 3Show 3 lines after
-B 3Show 3 lines before
-C 3Show 3 lines around

Filtering

-vInvert match
-wMatch whole words
-EExtended regex

File Selection

--include="*.js"Only search .js files
--exclude-dir=node_modulesSkip directory
-ISkip binary files

Common Combos

grep -rn "TODO" .Find TODOs with line #
grep -rl "pattern" .List files with match
grep -E "a|b" fileMatch a OR b

Downloadable Image Preview

Failed to generate preview

Basic Usage

grep (Global Regular Expression Print) searches for patterns in files and outputs matching lines. The basic syntax is straightforward:

bash
# 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:

OptionDescriptionExample
-iCase-insensitive searchgrep -i "error" log.txt
-r, -RRecursive search in directoriesgrep -r "TODO" ./src/
-nShow line numbersgrep -n "function" app.js
-vInvert match (show non-matching lines)grep -v "#" config.txt
-cCount matching linesgrep -c "error" log.txt
-lShow only filenames with matchesgrep -l "import" *.js
-LShow only filenames without matchesgrep -L "test" *.js
-wMatch whole words onlygrep -w "error" log.txt
-xMatch entire linegrep -x "OK" status.txt
-EExtended regex (same as egrep)grep -E "err|warn" log.txt
-FFixed strings (no regex, faster)grep -F "[ERROR]" log.txt
-PPerl-compatible regex (PCRE)grep -P "\d{3}-\d{4}" file.txt
bash
# 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" *.js

Output Control Options

Control what grep outputs and how context is displayed:

OptionDescriptionExample
-A NUMShow NUM lines after matchgrep -A 3 "error" log.txt
-B NUMShow NUM lines before matchgrep -B 2 "error" log.txt
-C NUMShow NUM lines of context (before & after)grep -C 2 "error" log.txt
-oShow only matching part of linegrep -o "[0-9]+" data.txt
-HAlways print filename with matchgrep -H "error" log.txt
-hNever print filenamegrep -h "error" *.log
--colorHighlight matches in colorgrep --color=auto "error" log.txt
-qQuiet mode (exit status only)grep -q "error" log.txt && echo "Found"
bash
# 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!"
fi

File Selection Options

Control which files grep searches:

OptionDescriptionExample
--includeOnly search files matching patterngrep -r --include="*.js" "func"
--excludeSkip files matching patterngrep -r --exclude="*.min.js" "func"
--exclude-dirSkip directories matching patterngrep -r --exclude-dir=node_modules "func"
--include-dirOnly search in matching directoriesgrep -r --include-dir=src "func"
-ISkip binary filesgrep -rI "pattern" .
bash
# 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/
Tip
For faster searches in Git repositories, consider using 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

ClassEquivalentMatches
[[: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:]]PunctuationPunctuation characters
[[:xdigit:]][0-9a-fA-F]Hexadecimal digits

Quantifiers

QuantifierDescriptionExample
*Zero or moregrep "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 timesgrep -E "[0-9]{4}" (4 digits)
{n,}n or more timesgrep -E "a{2,}" (aa, aaa...)
{n,m}Between n and m timesgrep -E "[0-9]{2,4}" (2-4 digits)

Anchors & Boundaries

AnchorDescriptionExample
^Start of linegrep "^Error" (lines starting with Error)
$End of linegrep "done$" (lines ending with done)
\bWord boundarygrep "\bword\b" (whole word)
\BNon-word boundarygrep "\Bword" (word within word)
bash
# 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.txt

Practical Examples for Developers

Searching in a Codebase

bash
# 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

bash
# 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.log

Configuration File Search

bash
# 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

bash
# 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" {} \;
Warning
Be careful when searching in large codebases. Use --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 insensitive
  • grep -r - Recursive search
  • grep -n - Show line numbers
  • grep -v - Invert match
  • grep -l - Files with matches only
  • grep -c - Count matches
  • grep -E - Extended regex
  • grep -o - Show only matching part
  • grep -A/-B/-C - Context lines
  • grep --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.

Related Articles