grep Command Cheatsheet
The grep command searches for lines that match a given text pattern in one or more files. It is an extremely useful tool for filtering output and finding specific information within text files.
Common Syntax
grep [OPTIONS] "PATTERN" [FILE]`PATTERN` is the text or regular expression (regex) you are looking for. `FILE` is the name of the file(s) to search.
Key `grep` Options
| Option | Description | Example |
|---|---|---|
-i | Performs a case-insensitive search. | grep -i "error" /var/log/syslog |
-r | Performs a recursive search through subdirectories. | grep -r "TODO" . |
-n | Displays the line number of each match. | grep -n "main" app.js |
-v | Inverts the match, showing lines that do **not** contain the pattern. | grep -v "#" config.ini |
-l | Only prints the names of files that contain a match, not the matching lines. | grep -l "function" *.js |
-L | Only prints the names of files that do **not** contain a match. | grep -r -L "TODO" . |
-c | Only prints a count of matching lines for each file. | grep -c "GET" access.log |
Using `grep` with Pipelines
`grep` is often used with pipes (`|`) to filter the output of other commands.
# Find all running processes and filter for 'nginx'
ps aux | grep nginx
# Find files and directories containing the word 'config', and only show files
find . -name "*config*" | grep -v 'd$'
# List all files in the current directory and subdirectories that do not contain 'SEARCH_STRING'
find . -type f -print0 | xargs -0 grep -L "SEARCH_STRING"