- Home
-
Grep Command
Grep Command Cheatsheet
Comprehensive guide to grep commands covering basic options, regular expressions, wildcards, character classes, quantifiers, POSIX classes, and advanced pattern matching for efficient text search in Linux. Master grep for log analysis, text processing with sed, and VPS server management.
Free account required
Grep Syntax
$ grep [OPTIONS] PATTERN [FILE...]
$ grep [OPTIONS] -e PATTERN ... [FILE...]
$ grep [OPTIONS] -f PATTERN_FILE ... [FILE...]
Grep searches each FILE or standard input for PATTERN. By default, grep prints the matching lines. Essential for Linux system administration and VPS server troubleshooting.
Table of Contents
Common Grep Options
Option | Description | Example |
---|---|---|
-i | Ignore case distinctions | $ grep -i 'pattern' file.txt |
-v | Invert match (select non-matching lines) | $ grep -v 'pattern' file.txt |
-n | Print line numbers with output | $ grep -n 'pattern' file.txt |
-c | Count matching lines | $ grep -c 'pattern' file.txt |
-l | List filenames with matches | $ grep -l 'pattern' *.txt |
-L | List filenames without matches | $ grep -L 'pattern' *.txt |
-r or -R | Recursive search in directories | $ grep -r 'pattern' /path/to/dir/ |
-w | Match whole words only | $ grep -w 'word' file.txt |
-x | Match whole lines only | $ grep -x 'exact line' file.txt |
-o | Show only matching part of line | $ grep -o 'pattern' file.txt |
-A NUM | Print NUM lines after match | $ grep -A 3 'pattern' file.txt |
-B NUM | Print NUM lines before match | $ grep -B 2 'pattern' file.txt |
-C NUM | Print NUM lines before and after | $ grep -C 2 'pattern' file.txt |
-e | Specify multiple patterns | $ grep -e 'pat1' -e 'pat2' file.txt |
-f FILE | Read patterns from file | $ grep -f patterns.txt file.txt |
-E | Extended regex (egrep) | $ grep -E 'pat1|pat2' file.txt |
-F | Fixed strings (fgrep) | $ grep -F 'literal$tring' file.txt |
-P | Perl-compatible regex | $ grep -P '\d{3}-\d{3}' file.txt |
-m NUM | Stop after NUM matches | $ grep -m 5 'pattern' file.txt |
--color | Highlight matches in color | $ grep --color 'pattern' file.txt |
Common Use Cases
Basic Text Search
$ grep 'search_term' filename
Search for a simple text pattern in a file
Case-Insensitive Search
$ grep -i 'error' /var/log/syslog
Find all occurrences regardless of case (Error, ERROR, error). Essential for analyzing server logs and debugging issues.
Recursive Directory Search
$ grep -r 'function_name' /path/to/project/
Search through all files in a directory recursively. Combine with Linux commands for powerful file operations.
Count Occurrences
$ grep -c 'pattern' file.txt
Count how many lines contain the pattern
Show Line Numbers
$ grep -n 'TODO' *.php
Display line numbers where pattern appears
Context Lines (Before/After/Around)
$ grep -A 3 -B 2 'error' log.txt # 2 before, 3 after
$ grep -C 5 'exception' log.txt # 5 lines before and after
Show surrounding context around matches
Multiple Patterns (OR Logic)
$ grep -E 'error|warning|critical' /var/log/syslog
$ grep -e 'pattern1' -e 'pattern2' file.txt
Search for multiple patterns simultaneously
Exclude/Invert Match
$ grep -v 'comment' code.js # Show lines NOT containing 'comment'
$ grep -v '^#' config.conf # Exclude comment lines
Display lines that don't match the pattern
Search by File Type
$ grep -r --include="*.php" 'class' /var/www/
$ grep -r --exclude="*.min.js" 'function' ./src/
Filter search by file extension. Perfect for searching web applications on your VPS hosting.
List Only Filenames
$ grep -l 'pattern' *.txt # Files with matches
$ grep -L 'pattern' *.txt # Files without matches
Show only filenames instead of matching lines
Whole Word Match
$ grep -w 'cat' file.txt # Matches 'cat' but not 'category'
Match complete words only
Pipe with Other Commands
$ ps aux | grep nginx
$ cat access.log | grep '404' | wc -l
Combine grep with other command outputs. Use Port Scanner and DNS Lookup tools for network diagnostics.
Regular Expression Wildcards
Wildcard | Description | Example |
---|---|---|
. | Match any single character except newline | $ grep 'c.t' file.txt |
? | Match 0 or 1 of the preceding character | $ grep -E 'colou?r' file.txt |
* | Match 0 or more of the preceding character | $ grep 'ab*c' file.txt |
+ | Match 1 or more of the preceding character | $ grep -E 'ab+c' file.txt |
Character Classes
Class | Description | Example |
---|---|---|
[A-Za-z] | Any lowercase or uppercase letter | $ grep '[A-Z]' file.txt |
[0-9] | Any digit (number) | $ grep '[0-9]' file.txt |
[0-9A-Za-z] | Any lowercase or uppercase letter or digit | $ grep '[0-9A-Za-z]' file.txt |
[^...] | Negation - match anything NOT in the brackets | $ grep '[^0-9]' file.txt |
Quantifiers
Quantifier | Description | Example |
---|---|---|
{n} | Matches exactly n times | $ grep -E '[0-9]{3}' file.txt |
{n,} | Matches n or more times | $ grep -E '[a-z]{5,}' file.txt |
{,m} | Matches up to m times (maximum) | $ grep -E '[0-9]{,3}' file.txt |
{n,m} | Matches between n and m times (minimum, maximum) | $ grep -E '[a-z]{3,6}' file.txt |
POSIX Character Classes
Class | Description | Example |
---|---|---|
[:alpha:] | Matches any alphabetical character (either upper or lower case) | $ grep '[[:alpha:]]' file.txt |
[:alnum:] | Matches any alphanumeric character (a-z, A-Z, 0-9) | $ grep '[[:alnum:]]' file.txt |
[:digit:] | Matches any numerical digit (0-9) | $ grep '[[:digit:]]' file.txt |
[:lower:] | Matches any lowercase alphabetical character (a-z) | $ grep '[[:lower:]]' file.txt |
[:upper:] | Matches any uppercase alphabetical character (A-Z) | $ grep '[[:upper:]]' file.txt |
[:punct:] | Matches any punctuation character | $ grep '[[:punct:]]' file.txt |
[:space:] | Matches any whitespace character (space, tab, newline, etc.) | $ grep '[[:space:]]' file.txt |
[:print:] | Matches any printable character | $ grep '[[:print:]]' file.txt |
[:blank:] | Matches space or tab characters | $ grep '[[:blank:]]' file.txt |
Position Anchors
Anchor | Description | Example |
---|---|---|
^ | Beginning of line | $ grep '^Error' log.txt |
$ | End of line | $ grep 'done$' log.txt |
^$ | Empty line (start and end with nothing between) | $ grep '^$' file.txt |
\< | Start of word | $ grep '\<word' file.txt |
\> | End of word | $ grep 'word\>' file.txt |
\b | Word boundary (start or end of word) | $ grep '\bword\b' file.txt |
BRE, ERE & PCRE
Basic Regular Expressions (BRE)
Default grep behavior. Unless preceded by a backslash, these characters have no special meaning. Ideal for simple pattern matching in log files.
$ grep 'pattern' file.txt
$ echo "hello world" | grep 'h.*o'
Characters: ^ $ . [ ] * \ ( ) { }
Extended Regular Expressions (ERE)
Activated with grep -E
or egrep
. ERE gives each of these characters a unique meaning:
$ grep -E 'pattern1|pattern2' file.txt
$ egrep '(color|colour)' file.txt
$ grep -E '[0-9]{3}-[0-9]{3}-[0-9]{4}' phonebook.txt
Additional characters: ? + | ( )
Perl Compatible Regular Expressions (PCRE)
Activated with grep -P
. Additional anchors, character classes, lookahead, lookbehind, conditional expressions, comments, and other features are available in PCRE. Powerful for complex server monitoring tasks.
$ grep -P '\d{3}-\d{3}-\d{4}' phonebook.txt
$ grep -P '(?<=@)\w+' emails.txt
$ grep -P '\b\w{5}\b' file.txt
Features: \d \w \s \D \W \S (?=...) (?!...) (?<=...) (?<!...)
Related Cheatsheets
Master Grep on High-Performance VPS
Use grep for server log analysis, debugging, and system monitoring on reliable VPS infrastructure. Explore our curated VPS providers, compare performance metrics, and find the perfect hosting for your Linux workloads. Check out our server management tools.