Grep examples: Perl-Compatible Regular Expressions

Grep examples: Perl-Compatible Regular Expressions

Last updated:
Table of Contents

All examples run under grep version 3 on Linux (ubuntu)

Match regex

Return the lines containing the given regex in the given file(s)

Example: lines that contain "foobar" followed by a digit:

$ grep -P 'foo\d+' myfile.txt

grep-simple-match-regex Matched 2 lines that contain the pattern

Match whole line

Return the lines that fully match the given regex

Use --line-regexp modifier

Example: lines that fully match "foobar" followed by a digit:

$ grep --line-regexp -P 'foo\d+' myfile.txt

match-whole-line-grep Only the line that fully matches the regex is returned

Not matching regex

Return lines not containing the given regex.

Use -v modifier

Example: lines that do not contain "foo" followed by digits

$ grep -v -P 'foo\d+' myfile.txt 

Match raw string

To match a fixed string (i.e. don't interpret any characters as special characters or modifiers)

Use -F modifier

$ grep -F '()' myfile-special-chars.txt

matching-raw-text

OR operator

A simple | between patterns:

Example: lines starting with "foo" OR ending in "bar":

$ grep -P '^foo|bar$' myfile.txt

grep-regex-or-operator Simple OR behaviour

Repeat N times

Use {N}

Example: lines containing exactly 2 digits:

$ grep -P '\d{2}' myfile.txt

two-digits Only lines with exactly 2 digits are a match

Character classes

Assuming perl-compatible regex (i.e. using the -P modifier)

Class Description Equivalent chars
\wAlphanumeric characters plus underscore (_)[A-Za-z0-9_]
\WEverything NOT \w[^A-Za-z0-9_]
\dDigits[0-9]
\sWhitespace characters[ \t\r\n\v\f]

Escape characters

To escape any of the special characters .?*+{|()[\^$ use a backslash \:

Example: match a literal '(' character

$ grep -P '\(' myfile.txt

grep-regex-escape-special-characters Matched a literal (

Search 2 files

Use -- at the end of the pattern and pass the file names:

$ grep -P 'foo.+' -- file1.txt file2.txt

grep-regex-match-two-files Use -- after the pattern to match multiple files

Type comparison

Basic Regex Extended Regex Perl-compatible Regex
ModifierNo modifier-e-P
EscapingSpecial characters lose their special meaning when not escapedSpecial characters lose their special meaning when escapedSpecial characters lose their special meaning when escaped
Character classesSupports character classes such as [[:alnum:]]Supports character classes such as [[:alnum:]]Supports character classes such as \w, \d in addition to classes such as [[:alnum:]]

grep: invalid option -- P

PCRE is not available on BSD grep (such as the MacOS distribution).

Use extended regexes (-E) instead: Grep examples: Extended Regular Expressions

Dialogue & Discussion