grep#
General Usage#
grep <options> <pattern> <file>Common Flags#
-i, --ignore-case: Ignore case distinctions.-v, --invert-match: Invert the sense of matching, selecting non-matching lines.-l, --files-with-matches: Print only the names of files with matching lines.-q, --quiet, --silent: Do not write anything to standard output. Exit immediately with zero status if any match is found.-n, --line-number: Prefix each line of output with its 1-based line number.-E, --extended-regexp: Interpret patterns as extended regular expressions (ERE).- eg.
grep -E '<pattern1>|<pattern2>|...' <file>
- eg.
-r, --recursive: Read all files under each directory, recursively.-A <num>, --after-context=<num>: Print<num>lines of trailing context after matching lines.-B <num>, --before-context=<num>: Print<num>lines of leading context before matching lines.-C <num>, --context=<num>: Print<num>lines of output context.
POSIX Character Classes#
Used within bracket expressions [ ].
[[:space:]]: Whitespace characters (space, tab, etc.)[[:digit:]]: Digits0-9[[:alpha:]]: Alphabetic charactersa-z,A-Z[[:alnum:]]: Alphanumeric characters (alphabetic and numeric)
Exit Codes#
0: One or more matches found.1: No matches found.2: An error occurred (eg. file not found).
Tips#
-l(List Files): Use this when you only need to know which files contain the pattern, rather than the matching lines themselves.- eg.
grep -l "TODO" *.md
- eg.
--: Use this when the search pattern starts with a dash (-) to preventgrepfrom interpreting it as an option.- eg.
<some-unfamiliar-command> --help | grep -- --<flagname>
- eg.