How To Use Grep?

Search for a pattern in a file: `grep “pattern” file.txt`

Search for a pattern in multiple files: `grep “pattern” file1.txt file2.txt`

Search recursively in a directory: `grep -r “pattern” /path/to/dir`

Ignore case: `grep -i “pattern” file.txt`

Show line numbers: `grep -n “pattern” file.txt`

Match whole words only: `grep -w “pattern” file.txt`

Invert the match: `grep -v “pattern” file.txt`

Count matching lines: `grep -c “pattern” file.txt`

Show only matching text: `grep -o “pattern” file.txt`

Search using a regular expression: `grep -E “pat1|pat2” file.txt`

Search for lines starting with text: `grep “^pattern” file.txt`

Search for lines ending with text: `grep “pattern$” file.txt`

Search in command output: `command | grep “pattern”`

Search and include context lines before and after: `grep -B 2 -A 2 “pattern” file.txt`

List files containing matches: `grep -l “pattern” *.txt`

List files without matches: `grep -L “pattern” *.txt`

Suppress error messages: `grep -s “pattern” file.txt`

Use fixed-string search: `grep -F “pattern” file.txt`

Search compressed files with zgrep: `zgrep “pattern” file.gz`

Combine common options: `grep -rinw “pattern” /path/to/dir`

Suggested for You

Trending Today