# grep
grep (Global Regular Expression Print) is a [[Command Line Interface (CLI)]] utility for searching plain-text data for lines matching a regular expression. Originally written by Ken Thompson for [[Unix]] in 1973, it remains one of the most widely used command-line tools across all [[POSIX]]-compatible systems.
## Variants
- **grep**: Basic regular expressions (BRE)
- **egrep / grep -E**: Extended regular expressions (ERE)
- **fgrep / grep -F**: Fixed string matching (no regex)
- **pcregrep**: Perl-compatible regex
## Common usage
```sh
# Basic search
grep "pattern" file.txt
# Recursive search in directory
grep -r "pattern" path/
# Case-insensitive
grep -i "pattern" file.txt
# Show line numbers
grep -n "pattern" file.txt
# Count matches
grep -c "pattern" file.txt
# Show only filenames with matches
grep -l "pattern" *.txt
# Invert match (lines NOT matching)
grep -v "pattern" file.txt
# Context lines (before/after/both)
grep -B 2 -A 2 "pattern" file.txt
grep -C 3 "pattern" file.txt
# Extended regex
grep -E "pattern1|pattern2" file.txt
# Fixed string (no regex)
grep -F "literal.string" file.txt
```
## Useful options
| Option | Description |
|--------|-------------|
| `-r` / `-R` | Recursive search |
| `-i` | Case-insensitive |
| `-n` | Show line numbers |
| `-c` | Count matches per file |
| `-l` | List filenames only |
| `-v` | Invert match |
| `-w` | Match whole words |
| `-x` | Match whole lines |
| `-o` | Print only matched parts |
| `-E` | Extended regex (ERE) |
| `-F` | Fixed string (literal) |
| `-P` | Perl-compatible regex |
## Piping patterns
grep is commonly combined with other commands via pipes:
```sh
# Filter process list
ps aux | grep nginx
# Filter log output
tail -f /var/log/syslog | grep "error"
# Chain with other tools
cat file.txt | grep "TODO" | sort | uniq
```
## Modern alternatives
- **[[ripgrep]]**: Faster, respects `.gitignore`, Unicode-aware — the most popular modern replacement
- **ag (The Silver Searcher)**: Fast code search tool
- **ack**: Designed for searching source code
## References
- https://www.gnu.org/software/grep/manual/grep.html
- https://en.wikipedia.org/wiki/Grep
## Related
- [[ripgrep]]
- [[fzf]]
- [[Command Line Interface (CLI)]]
- [[Shell]]
- [[Bash]]
- [[Zsh (Z Shell)]]
- [[Unix]]
- [[Linux]]
- [[POSIX]]