Grep examples: Perl-Compatible Regular Expressions
Last updated:- Match regex
- Match whole line
- Not matching regex
- Match raw string
- OR operator
- Repeat N times
- Character classes
- Escape characters
- Search 2 files
- Type comparison
- grep: invalid option -- P
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
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
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
OR operator
A simple | between patterns:
Example: lines starting with "foo" OR ending in "bar":
$ grep -P '^foo|bar$' myfile.txt
Simple OR behaviour
Repeat N times
Use {N}
Example: lines containing exactly 2 digits:
$ grep -P '\d{2}' myfile.txt
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 |
|---|---|---|
\w | Alphanumeric characters plus underscore (_) | [A-Za-z0-9_] |
\W | Everything NOT \w | [^A-Za-z0-9_] |
\d | Digits | [0-9] |
\s | Whitespace 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
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
Use -- after the pattern to match multiple files
Type comparison
| Basic Regex | Extended Regex | Perl-compatible Regex | |
|---|---|---|---|
| Modifier | No modifier | -e | -P |
| Escaping | Special characters lose their special meaning when not escaped | Special characters lose their special meaning when escaped | Special characters lose their special meaning when escaped |
| Character classes | Supports 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