Advanced grep: recursive search, context, PCRE patterns, and file filtering.
low risk
Beyond basic pattern matching, grep supports recursive directory search, context lines around matches, Perl-compatible regex (PCRE), and filtering by file type. Used heavily for log analysis, code search, and configuration auditing.
| Flag | Meaning |
|---|---|
-r/-R | Recursive directory search |
-l --files-with-matches | Print only filenames, not matches |
-c --count | Print match count per file |
-A/-B/-C | Lines After/Before/Context of match |
-P --perl-regexp | Perl-compatible regex (PCRE) |
--include | Only search files matching pattern |
-v --invert-match | Print non-matching lines |
grep -rn 'password' /etc/ --include='*.conf' 2>/dev/nullFind password references in all config files · explain & risk-check →grep -A 5 -B 2 'CRITICAL' /var/log/app.logShow 5 lines after and 2 before each CRITICAL match · explain & risk-check →grep -P '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' access.logExtract IPv4 addresses using PCRE · explain & risk-check →grep -rL 'strict_mode' /etc/mysql/conf.d/Find config files that DON'T have strict_mode · explain & risk-check →grep -c 'ERROR' /var/log/*.log | sort -t: -k2 -rn | head -5Files with most ERROR lines · explain & risk-check →Use `grep -rn 'pattern' . --include='*.py' --exclude-dir='.git'` for code search — the include/exclude flags prevent searching binaries and version control directories.
Reference text is hand-written and may be incomplete — check man grep for your version. Test destructive commands on a non-production system first.