cheat-sheets

Grep

Grep is a command-line utility for searching plain-text data for lines matching a regular expression. Its name comes from the ed command g/re/p (globally search for a regular expression and print). It is available on Linux and all Unix-like systems. See also Sed and Awk.

Common Options #

OPTIONDESCRIPTION
-iIgnore case
-vInvert match (lines that do NOT match)
-r / -RRecurse into directories (-R follows symlinks)
-nShow line numbers
-cCount matching lines
-l / -LList files with / without matches
-wMatch whole words only
-xMatch whole lines only
-oPrint only the matched part
-hHide file names
-A <N> / -B <N> / -C <N>Show N lines after / before / around a match
-EExtended regex (same as egrep)
-FFixed strings, no regex (fastest)
-PPerl-compatible regex (lookaheads, \d, \K)
-qQuiet, only set the exit code
-m <N>Stop after N matches
--include=<GLOB> / --exclude=<GLOB>Filter files by name
--exclude-dir=<DIR>Skip a directory
--color=autoHighlight matches

Examples #

COMMANDDESCRIPTION
grep -rn "TODO" .Find TODOs with file and line number
grep -rIl "password" /etc 2>/dev/nullList text files mentioning a word, skip binaries
grep -v '^\s*#' file.conf | grep -v '^\s*$'Show config without comments and blank lines
grep -E "error|warn" app.logMatch either word
grep -ow "[0-9]\{1,3\}\(\.[0-9]\{1,3\}\)\{3\}" fileExtract IPv4-looking strings
grep -Po '(?<=version=)\S+' filePrint text after a prefix (lookbehind)
grep -rn --include="*.py" "import os" .Search only Python files
grep -C 3 "Exception" app.logMatch with 3 lines of context
grep -c "" fileCount lines in a file
grep -f patterns.txt fileUse patterns from a file
ps aux | grep [n]ginxSearch processes without matching grep itself
docker logs <CONTAINER> 2>&1 | grep -i errorFilter container logs (stderr must be merged)

Regex Quick Reference #

PATTERNMEANING
.Any single character
^ / $Start / end of line
* + ?0 or more / 1 or more / 0 or 1 (+ and ? need -E)
{n,m}Between n and m repeats (-E)
[abc] / [^abc]Character in / not in the set
[[:digit:]] [[:space:]] [[:alpha:]]POSIX classes
(a|b)Alternation (-E)
\bWord boundary
Search all sheets

Tip: / or Ctrl/Cmd+K to open, Esc to close.