grep
Quick Reference
Command Name:
grep
Category:
text processing
Platform:
linux
Basic Usage:
Common Use Cases
Syntax
grep [options] pattern [file...]
Options
Option | Description |
---|---|
-i, --ignore-case | Ignore case distinctions in patterns and input data |
-v, --invert-match | Select non-matching lines |
-w, --word-regexp | Match only whole words |
-r, --recursive | Read all files under each directory recursively |
-n, --line-number | Prefix each line of output with its line number |
-l, --files-with-matches | Print only names of files with matching lines |
-L, --files-without-match | Print only names of files with no matching lines |
-c, --count | Print only a count of matching lines per file |
-A NUM, --after-context=NUM | Print NUM lines of trailing context after matching lines |
-B NUM, --before-context=NUM | Print NUM lines of leading context before matching lines |
-C NUM, --context=NUM | Print NUM lines of context before and after matches |
-E, --extended-regexp | Use extended regular expressions |
-F, --fixed-strings | Interpret patterns as fixed strings, not regular expressions |
-P, --perl-regexp | Interpret patterns as Perl-compatible regular expressions |
--include=GLOB | Search only files that match GLOB pattern |
--exclude=GLOB | Skip files that match GLOB pattern |
--color[=WHEN] | Surround matches with color markers (auto, always, never) |
-o, --only-matching | Show only the part of a line that matches the pattern |
-q, --quiet, --silent | Suppress all normal output (exit with status 0 if match found) |
Examples
How to Use These Examples
The examples below show common ways to use the grep
command. Try them in your terminal to see the results. You can copy any example by clicking on the code block.
Basic Examples:
grep "error" logfile.txt
Searches for the word "error" in logfile.txt. This is the most basic usage of grep that displays all lines containing the specified pattern.
grep -i "warning" logfile.txt
Performs a case-insensitive search for "warning" in logfile.txt. The -i option ignores case distinctions, matching both "Warning", "WARNING", and "warning".
grep -r "TODO" /path/to/project
Recursively searches for "TODO" in all files under the specified directory. The -r option enables recursive searching through all subdirectories.
grep -v "error" logfile.txt
Inverts the match, showing all lines that do NOT contain "error". The -v option inverts the sense of matching, selecting non-matching lines.
Advanced Examples:
grep -E "error|warning|critical" logfile.txt
Searches for multiple patterns using regular expressions. The -E option enables extended regular expressions, allowing the use of the OR operator (|) to match any of the specified patterns.
grep -n "function" script.js
Shows line numbers for matching lines. The -n option prefixes each matching line with its line number, making it easier to locate the match in the file.