grep — Context & Recursive

Context Flags

Show 3 lines after each match
grep -A 3 'ERROR' /var/log/syslog
Show 2 lines before each match
grep -B 2 'FATAL' app.log
Show 5 lines of context (before and after)
grep -C 5 'Exception' app.log
Preserve color through pipe to pager
grep --color=always 'pattern' | less -R
Show function definition around match
grep -nP -B2 -A10 'def report_to_wazuh' mail-detector.py
Count matches per file (files with >5 xrefs)
grep -rcP --include='*.adoc' 'xref:' docs/modules/ROOT/pages/ | awk -F: '$2 > 5'

Extraction (-o and \K)

Extract only the matched portion
grep -oP '\d{1,3}(\.\d{1,3}){3}' /etc/hosts
# Output: 10.50.1.50
#         10.50.1.90
#         127.0.0.1
Extract with \K reset — captures only the value after the key
grep -oP 'port-\w+: '\''\K[^'\'']+' docs/antora.yml
# Output: 25
#         587
#         993
Recursive search through a directory tree
grep -r 'pattern' /etc/
Recursive with file glob filter and line numbers
grep -rn --include='*.py' 'import' .
Multiple include globs
grep -rnP --include='*.{yaml,yml}' 'password' /etc/
Recursive excluding specific directories
grep --exclude-dir={.git,node_modules,vendor} -rn 'TODO' .
Files-only mode — list files containing pattern
grep -rlP --include='*.adoc' ':toc:' docs/
# STD-004 violation: Antora provides sidebar TOC globally
Invert files — list files NOT containing pattern
grep -rLP --include='*.adoc' ':description:' docs/modules/ROOT/pages/
# Missing :description: header — find non-compliant pages