Bash

grep

grep commands for searching text patterns in files.

28 commands
Windows MacOS Linux
#text-processing #search

Basic Search

Search for pattern in a file
grep "pattern" file.txt
Case-insensitive search
grep -i "pattern" file.txt
Match whole words only
grep -w "word" file.txt
Count matching lines
grep -c "pattern" file.txt
Show line numbers with matches
grep -n "pattern" file.txt
Show lines that do not match
grep -v "pattern" file.txt

Regex Patterns

Extended regex, match foo or bar
grep -E "foo|bar" file.txt
Match lines starting with Start
grep -E "^Start" file.txt
Match lines ending with end
grep -E "end$" file.txt
Match three consecutive digits
grep -E "[0-9]{3}" file.txt
Perl regex for decimal numbers
grep -P "\d+\.\d+" file.txt

File Filtering

Search in all .log files
grep "pattern" *.log
Search only Python files
grep --include="*.py" -r "def" .
Exclude backup files from search
grep --exclude="*.bak" -r "TODO" .
Skip a directory
grep --exclude-dir=node_modules -r "import" .

Output Control

Show only filenames with matches
grep -l "pattern" *.txt
Show filenames without matches
grep -L "pattern" *.txt
Print only the matched text
grep -o "pattern" file.txt
Show 3 lines after each match
grep -A 3 "pattern" file.txt
Show 2 lines before each match
grep -B 2 "pattern" file.txt
Show 2 lines of context around match
grep -C 2 "pattern" file.txt

Recursive Search

Search recursively in a directory
grep -r "pattern" /path/to/dir
Recursive search with line numbers
grep -rn "TODO" .
List JS files containing function
grep -rl "function" --include="*.js" .
Handle filenames with spaces
grep -rZ "pattern" . | xargs -0 ls -l

Quick Commands

Recursively search for a pattern in a directory
grep -r "pattern" /path/
Case-insensitive search in a file
grep -i "pattern" file.txt
Search with line numbers displayed
grep -n "pattern" file.txt