Advanced · 12 min · practise every command in the built-in terminal

Regular Expressions (Regex)

Regex are patterns for matching text. Used with grep, sed, awk, and many programs.

Basic characters

PatternMatches
.Any single character
*Zero or more of previous
+One or more of previous
?Zero or one of previous
^Start of line
$End of line
\bWord boundary
\dDigit (in PCRE)
\wWord character
\sWhitespace

Character classes

[abc]          # a, b, or c
[^abc]         # Not a, b, or c
[a-z]          # Lowercase letter
[A-Z]          # Uppercase letter
[0-9]          # Digit
[a-zA-Z0-9]   # Alphanumeric

Quantifiers

a{3}           # Exactly 3 a's: aaa
a{2,5}         # 2 to 5 a's
a{2,}          # 2 or more a's

Groups and alternation

(cat|dog)      # cat or dog
(abc)+         # One or more 'abc'

With grep

grep 'pattern' file              # Basic regex
grep -E 'pattern' file           # Extended regex
grep -P 'pattern' file           # Perl-compatible regex

grep '^[A-Z]' file               # Lines starting with uppercase
grep '[0-9]\{3\}-[0-9]\{4\}' file  # Phone numbers
grep -E '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' emails.txt

Practical examples

# Find IP addresses
grep -E '\b[0-9]{1,3}(\.[0-9]{1,3}){3}\b' file.txt

# Find email addresses
grep -E '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]+' file.txt

# Lines with exactly 5 characters
grep -E '^.{5}$' file.txt

Practice tasks

  1. Use grep with regex to find all lines in /etc/passwd that start with a letter
  2. Find all lines in /etc/passwd that end with /bin/bash or /bin/sh
  3. Find lines in /etc/passwd containing a UID made only of digits
  4. Find lines matching either 'root' or 'student' using alternation

Commands in this lesson

Advanced Commands