Skip to content

~/avetyan.com/cheatsheets

Cheat sheets

Regex cheat sheet

Regular expressions for grep, sed and awk: the syntax, how basic, extended and Perl-style regex differ, and patterns for IPs, dates and log lines.

3 min read


Characters

PatternMatches

Anchors

PatternMatches

Repeats

PatternMatches

Groups

PatternMeaning

BRE, ERE, PCRE

BREEREPCRE

When a pattern “doesn’t work” in grep or sed, add -E first.

grep, sed, awk

bash
grep -E '^(GET|POST) ' access.log
grep -oE '[0-9]+ms' app.log             # print only the match
grep -P '(?<=user=)\w+' app.log -o      # value after user=
grep -vE '^\s*(#|$)' nginx.conf         # drop comments and blank lines

sed -E 's/([0-9]{4})-([0-9]{2})-([0-9]{2})/\3.\2.\1/' dates.txt
sed -E 's/\s+$//' file                  # trailing whitespace
sed -E '/^\s*#/d' file                  # delete comment lines

awk '$9 ~ /^5[0-9][0-9]$/' access.log   # 5xx status codes
awk '!/^#/ && NF' file                  # skip comments and empty lines

Ready patterns

WhatERE pattern

The loose IP pattern also matches 999.1.1.1. Fine for finding addresses in logs, not for validating input.

Escaping

CharacterEscape when you mean it literally
bash
grep -F 'a.b*c' file                    # fixed string: no regex at all

Keep in mind

  • Single-quote patterns in the shell, so $, * and \ reach grep untouched.
  • Regex can’t parse JSON, HTML or nested structures reliably. Use jq or a real parser.
  • Test on real samples first: grep -nE 'pattern' file | head.

Comments

Sign in with Google, GitHub or Facebook to comment.

Loading comments…