Command library / grep
grep
Search text for lines that match a pattern
Prints the lines of a file (or of piped input) that match a pattern. It is the analyst's workhorse for logs: filter first, then count, sort or investigate. Quote patterns that contain spaces or special characters, otherwise the shell splits them into separate arguments.
Practice grepUsage
Options and flags
patterntext or regular expression to look for
filefile or directory to search (omit to read piped input)
-iignore upper/lower case
-vinvert: show lines that do NOT match
-nshow line numbers
-cprint only the number of matching lines
-r, -Rsearch directories recursively
-Eextended regular expressions (|, +, ?, ())
-wmatch whole words only
-llist only the names of files that contain a match
-oprint only the matching part of each line
-Ftreat the pattern as a fixed string, not a regex
-ANUMalso print NUM lines After each match
-BNUMalso print NUM lines Before each match
-CNUMalso print NUM lines of Context around each match
Examples
grep 'Failed password' /var/log/auth.logEvery failed SSH login attempt.
grep -i error app.log'error', 'Error' and 'ERROR' all match.
grep -c 'Failed password' /var/log/auth.logJust the count of failed logins.
grep -rn password /var/wwwHunt hard-coded passwords, with file and line number.
grep -v '^#' /etc/ssh/sshd_configThe config without comment lines.
Common mistakes
Without quotes the shell passes 'password' as a FILE name. Quote multi-word patterns.