INFO

grep regex is Perl-compatible (PCRE): refer to the VSCode regex for the core syntax. Always use the -P flag to enable PCRE mode. Without it, grep falls back to BRE (like SED).


Flags Cheatsheet

FlagDescription
-PEnable PCRE mode — use this always for VSCode-like syntax
-EEnable ERE mode (no PCRE, simpler alternative to -P)
-iCase-insensitive match
-nShow line numbers alongside matches
-rRecurse into subdirectories
-lPrint only filenames containing a match (not the lines)
-vInvert match — print lines that do not match
-oPrint only the matched portion, not the whole line
-cCount matching lines

How to Use Grep

CommandDescription
grep -P 'pattern' file.txtMatch pattern in a file
grep -rP 'pattern' ./dirRecursive search in a directory
grep -rPl 'pattern' ./dirList only files with a match
grep -Pn 'pattern' file.txtShow matches with line numbers
grep -Pv 'pattern' file.txtShow lines that do NOT match
grep -Po 'pattern' file.txtExtract only the matched text

Grep-Specific Notes

  • No \< / \> boundary syntax from SED — use \b as in VSCode
  • Lookaheads and lookbehinds are supported with -P:
grep -P 'foo(?=bar)' file.txt     # "foo" only if followed by "bar"
grep -P 'foo(?!bar)' file.txt     # "foo" only if NOT followed by "bar"
grep -P '(?<=@)\w+' file.txt      # word after "@" (e.g. domain in an email)

Exercises

Find lines containing an IPv4 address

grep -P '\b\d{1,3}(\.\d{1,3}){3}\b' file.txt

Extract all email addresses from a file

grep -Po '[\w.+-]+@[\w-]+\.[a-z]{2,}' file.txt

Find lines that do NOT contain a number

grep -Pv '\d' file.txt