How to Use grep to Search Text on Linux
Search through files and command output on Linux with grep — learn the most useful flags including case-insensitive, recursive, and inverted searches.
What Is grep?
grep (Global Regular Expression Print) searches text for lines matching a pattern and prints them. It's one of the most-used commands on Linux, essential for searching log files, code, config files, and command output.
Basic Usage
grep "error" app.log # find lines containing "error"
grep "404" /var/log/nginx/access.log
grep "root" /etc/passwd
Most Useful Flags
-i— case-insensitive search-r— recursive search through directories-v— invert match (show lines that do NOT match)-n— show line numbers-c— count matching lines-l— list only filenames with matches-w— match whole words only-A 3— show 3 lines after the match-B 3— show 3 lines before the match-C 3— show 3 lines before and after (context)
Practical Examples
# Case-insensitive search
grep -i "warning" /var/log/syslog
# Recursive search in all .py files
grep -r "import os" ~/projects/ --include="*.py"
# Show lines that don't contain "success"
grep -v "success" deploy.log
# Count how many times a pattern appears
grep -c "ERROR" app.log
# Show filename and line number
grep -rn "TODO" ~/projects/
# Show context around a match
grep -C 5 "Segmentation fault" /var/log/syslog
Using grep with Pipes
grep shines when combined with other commands using pipes:
ps aux | grep nginx # find nginx processes
ls -la | grep "^d" # list only directories
cat /etc/passwd | grep "/bin/bash" # users with bash shell
journalctl -u nginx | grep "error"
history | grep "git commit" # search command history
Extended Regular Expressions with -E
grep -E "error|warning|fatal" app.log # match multiple patterns
grep -E "^(GET|POST)" access.log # lines starting with GET or POST
grep -E "[0-9]{3}" access.log # three consecutive digits
Search for a Fixed String (No Regex)
grep -F "192.168.1.1" access.log # treat pattern as literal string
Use -F when your search string contains special regex characters like ., *, or [.