*ARGS.TECH | BLOG | How to use "grep": A practical Linux cheatsheet
Loading...
BLOG
How to use "grep": A practical Linux cheatsheet
Terminal: ~

# Master the Linux `grep` command. This cheatsheet covers

# everything from basic filtering to advanced regex,

# recursive search, and getting context around your matches.


# ----- Mastering `grep`: Basic Filtering -----


# The most common use: filter output from another command:

# (e.g., find a specific process)

xinit@localhost:~$ ps aux | grep 'nginx'


# Search for a string in a single file (case-sensitive):

xinit@localhost:~$ grep 'error' /var/log/syslog


# Search for a string, ignoring case:

xinit@localhost:~$ grep -i 'error' /var/log/syslog


# Search for lines that DO NOT match the pattern:

xinit@localhost:~$ grep -v 'debug' /var/log/app.log


# ----- Advanced Pattern Matching -----


# Recursively search for a pattern in a directory:

# -r: recursive, -n: show line number, -w: match whole word

xinit@localhost:~$ grep -rnw '/path/to/project' -e 'function_name'


# Use Extended Regular Expressions (ERE) with -E:

# (e.g., find 'error' or 'warning')

xinit@localhost:~$ grep -E 'error|warning' /var/log/app.log


# Search for lines starting with a specific word:

xinit@localhost:~$ grep '^start' /var/log/boot.log


# ----- Getting Context & Counting -----


# Show 3 lines AFTER each match:

xinit@localhost:~$ grep -A 3 'critical error' /var/log/nginx/error.log


# Show 3 lines BEFORE each match:

xinit@localhost:~$ grep -B 3 'exception' /var/log/app.log


# Show 3 lines BEFORE AND AFTER each match:

xinit@localhost:~$ grep -C 3 'segmentation fault' /var/log/kernel.log


# Simply count the number of matching lines:

xinit@localhost:~$ grep -c '404 Not Found' /var/log/nginx/access.log

www.args.tech
Top button
© *ARGS.TECH
2025
v 2.6.19