grep is a command-line utility used to search for text that matches a pattern in files or input. It's available on Linux, macOS, and other Unix-like systems, and is one of the most commonly used shell commands.
The name grep comes from the old Unix editor command:
g/re/p = "globally search for a regular expression and print matching lines."
Basic syntax
Examples
Find a word in a file:
Output:
Search without case sensitivity:
Matches:
Search recursively in a directory:
Searches all files in the current directory and its subdirectories.
Show line numbers:
Output:
Count matching lines:
Common options
| Option | Description |
|---|
-i | Ignore case |
-n | Show line numbers |
-r or -R | Search directories recursively |
-v | Show lines that do not match |
-c | Count matching lines |
-l | Show only filenames containing matches |
-w | Match whole words only |
-E | Use extended regular expressions |
Using regular expressions
Find lines that start with "Error":
Find lines ending with ".txt":
Find any 3-digit number:
Using grep with pipes
You can combine grep with other commands:
Shows running processes containing the word python.
Or:
Displays only log entries containing 404.
In short, grep filters text, making it easy to find lines that contain specific words or patterns. It's an essential tool for searching logs, source code, configuration files, and command output.