Regex for PCRE, grep, ripgrep, and sed

Regex patterns and command-line workflows for grep, ripgrep, sed, awk, and advanced PCRE-style features.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## grep, egrep, and ripgrep
grep whole word
grep -RInw 'error' ./logs

# Find full-word matches in files.

ripgrep ignore case
rg -n -i 'timeout|timed out' .

# Search recursively with ripgrep case-insensitively.

ripgrep with PCRE2
rg -n -P '(?<=ERROR: ).+' app.log

# Use lookbehind or advanced features through PCRE2 mode.

Invert match
grep -RInv '^\s*(#|$)' ./config

# Show lines that do not match a pattern.

Alternation in egrep style
grep -E 'warn|error|fatal' app.log

# Search for one of several tokens.

sed regex replacement
sed -E 's/[[:space:]]+/ /g' file.txt

# Replace all runs of whitespace with a single space.

awk regex condition
awk '/^[0-9]{4}-[0-9]{2}-[0-9]{2}/ { print }' file.txt

# Print lines matching a regex in awk.

## PCRE and Advanced Features
Atomic group in PCRE
(?>[A-Z][a-z]+)\s+\d+

# Avoid backtracking inside a grouped token.

Subroutine call
^(?<pair>\((?:[^()]++|(?&pair))*\))$

# Reuse part of the pattern as a subroutine.

Recursion
^\((?:[^()]++|(?R))*\)$

# Recursive pattern for balanced parentheses.

Conditional expression
^(?:(<))?\w+(?(1)>)$

# Branch based on whether a group matched.

Keep out / skip fail
\b(?:https?://\S+)(*SKIP)(*F)|\bTODO\b

# Skip over matched prefixes before continuing.

## sed and Stream Editing
Reformat date
sed -E 's/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/\2\/\3\/\1/'

# Convert YYYY-MM-DD into MM/DD/YYYY.

Trim trailing spaces
sed -E 's/[[:space:]]+$//' file.txt

# Remove trailing whitespace from each line.

Prefix non-empty lines
sed -E '/^$/! s/^/# /' notes.txt

# Add a prefix only to non-empty lines.

Extract quoted content
sed -En 's/.*"([^"]+)".*/\1/p' file.txt

# Print only the content inside double quotes on each line.

Recommended next

No recommendations yet.