Everyday options¶
grep 'string' file # lines containing string
grep -i 'string' file # ignore case
grep -n 'string' file # show line numbers
grep -v 'string' file # invert: lines NOT matching
grep -c 'string' file # count matching lines
grep -w 'run' file # whole-word match
grep -F 'a.b(c)' file # fixed string, no regex
grep -E 'foo|bar' file # extended regex (alternation, +, ?)
grep -o '[0-9]\+' file # print only the matching part
grep -l 'string' * # only names of files that match
grep -L 'string' * # names of files that do not
grep -A 4 'string' file # 4 lines of trailing context
grep -B 4 'string' file # 4 lines of leading context
grep -C 4 'string' file # both
Recursive¶
grep -rn 'TODO' src/ # recursive with line numbers
grep -riI 'string' . # ignore case, skip binary files
grep -r --include='*.py' 'import os' . # only some files
grep -r --exclude-dir=.git --exclude='*.min.js' 'apiKey' .
grep -rl '^#!/.*bash' . # find all bash scripts
Show a file without comments and blank lines¶
grep -v -e '^#' -e '^$' file.conf
grep -Ev '^\s*(#|$)' file.conf # also skips indented comments and whitespace-only lines
Regex quick reference (basic regular expressions)¶
| Pattern | Matches |
|---|---|
^ |
start of a line (^A) |
$ |
end of a line (A$) |
\ |
turns off special meaning of the next character (\^) |
[ ] |
any one of the enclosed characters ([aeiou], ranges [0-9]) |
[^ ] |
any one character except those enclosed |
. |
any single character |
* |
zero or more of the preceding item |
\{x,y\} |
between x and y of the preceding item (in -E mode: {x,y}) |
\{x\} |
exactly x |
\{x,\} |
x or more |
\< \> |
start / end of a word |
Examples¶
grep '^string' file # at the start of a line
grep 'string$' file # at the end
grep '^string$' file # lines consisting only of "string"
grep '^$' file # blank lines
grep '[Ss]tring' file # String or string
grep 'B[oO][bB]' file # BOB, Bob, BOb, BoB
grep '[0-9][0-9]' file # two digits in a row
grep '[^a-zA-Z0-9]' file # lines with anything other than letters/digits
grep '[0-9]\{3\}-[0-9]\{4\}' file # 555-1234 style
grep -E '[0-9]{3}-[0-9]{4}' file # same, extended syntax
grep '^.$' file # lines with exactly one character
grep '"string"' file # with double quotes (single-quote the pattern)
grep '"*string"*' file # with or without quotes
grep '^\.' file # lines starting with a dot
grep '^\.[a-z][a-z]' file # a dot then two lowercase letters
grep '\<50\>' file # the number 50 only (not 150, 502, ...)
grep '\<the\>' file # the word "the" only (not other, othello)
grep 'run[- ]time' *.txt # "run time" or "run-time"
grep -E 'sec_|ice_' /var/log/secure # either string
Use grep -P (Perl regex) if available for lookaheads and \d. Combine with find and xargs for large searches. For code trees, ripgrep (rg) is faster and respects .gitignore.