GREP Commands Cheatsheet — Essential Reference
grep is a powerful command-line utility for searching plain-text data sets for lines that match a regular expression. It's commonly used to filter output from other commands or to find specific text within files.
Master GREP with Top Reference Books
Level up your DevOps skills. Find the best guide books and cheatsheet references for your engineering stack.
Commands
| Command | Description | Example |
|---|---|---|
grep 'pattern' filename |
Searches for lines containing 'pattern' in 'filename'. | grep 'error' /var/log/syslog |
grep -i 'pattern' filename |
Performs a case-insensitive search for 'pattern'. | grep -i 'warning' app.log |
grep -r 'pattern' directory/ |
Recursively searches for 'pattern' in files within 'directory' and its subdirectories. | grep -r 'TODO' ~/projects/my_app/ |
grep -v 'pattern' filename |
Inverts the match, showing lines that *do not* contain 'pattern'. | grep -v 'debug' server.log |
grep -n 'pattern' filename |
Displays the line number along with the matching line. | grep -n 'function' script.py |
grep -c 'pattern' filename |
Counts the number of lines that match 'pattern'. | grep -c 'failed' auth.log |
grep -l 'pattern' directory/* |
Lists only the names of files that contain 'pattern'. | grep -l 'import React' src/*.js |
command | grep 'pattern' |
Pipes the output of 'command' to grep, filtering its output. | ps aux | grep 'nginx' |
Pro Tips
- Use `grep -E` or `egrep` for extended regular expressions (e.g., `|` for OR, `?` for 0 or 1 occurrence).
- Combine `grep` with `awk` or `sed` for more complex text processing and manipulation.
- Utilize `grep -P` for Perl-compatible regular expressions, offering advanced features like lookarounds.
- For faster searches on large files, consider using `zgrep` for gzipped files or `ack`/`ag` (the silver searcher) for codebases.
Frequently Asked Questions
What is grep used for?
grep is primarily used for searching text within files or streams of data. It helps users quickly locate specific lines that match a given pattern, making it invaluable for log analysis, code debugging, and general file content inspection.
How do I install grep?
grep is a standard Unix utility and is almost always pre-installed on Linux and macOS systems. On Windows, you can get it by installing Git Bash, Cygwin, or Windows Subsystem for Linux (WSL).