Ravindra BagaleCourses & study guides

Chapter 4: Linux Advanced Commands

4.1 Searching text: grep

grep prints lines that match a pattern.

Option Meaning
-i Ignore case
-r / -R Recursive search in directories
-n Show line numbers
-v Invert (lines that do NOT match)
-c Count matching lines
-l Only file names
-w Match whole word
-E Extended regex (alternation with a pipe symbol, +, ?)
-​A 3 / -​B 3 / -​C 3 Show 3 lines after / before / around
grep -i "error" /var/log/nginx/error.log
grep -rn "listen" /etc/nginx/
grep -v "^#" /etc/ssh/sshd_config | grep -v "^$"   # hide comments & blank lines
grep -c " 404 " /var/log/nginx/access.log          # how many 404s?
grep -E "Failed|Invalid" /var/log/auth.log         # Ubuntu SSH failures
sudo grep "Failed password" /var/log/secure         # AL2/CentOS (AL2023 uses journalctl)