Pcornel
Linux · Text Processing

Regular Expressions

Cheat sheet · https://pcornel.dk/topic.php?topic=2680

Back to the Topic

Answer

Regular expressions describe text patterns: . any character, * + ? repetition, [] character sets, ^ $ anchors, () groups and | alternation. grep uses basic (BRE) by default, grep -E extended (ERE), grep -P Perl syntax.

Remember

Anchor patterns (^error) to avoid false matches. In BRE, + ? | ( ) need a backslash — use -E instead. Quote regexes in single quotes so the shell does not expand them. Test on a small sample.

First checks

  • grep -E '^[0-9]{1,3}(\.[0-9]{1,3}){3}$' <file> — example: IPv4-looking lines
  • grep -o '<regex>' <file> — only the matched part
  • grep -c '<regex>' <file> — count matching lines
  • sed -E 's/<re>/<repl>/g' <file> — replace with extended regex

Verify in this order

pattern written and quoted → engine (BRE/ERE/PCRE) matches → only intended text matched → used for search or replace

Where it usually breaks

First mismatch in persistent intent → provider/parser/generator → kernel/userspace runtime → dependency/security context → logs/counters → consumer-visible read-back; preserve identity/native diagnostic/pre-state before mutation.

Read-only verification commands unless stated otherwise. Confirm syntax for your platform and release. Full reference: https://pcornel.dk/topic.php?topic=2680

Confirmation

Confirm action

Continue?