Overview

sed uses Basic Regular Expressions (BRE) by default.

Most Linux distributions also support Extended Regular Expressions (ERE) using:

sed -E '...'

Using -E usually makes expressions easier to read.


Matching

Match any line containing error:

sed '/error/p'

Beginning of line:

sed '/^root/p'

End of line:

sed '/localhost$/p'

Whole line:

sed '/^$/d'

Delete empty lines.


Character Classes

Digit:

[0-9]

Lowercase:

[a-z]

Uppercase:

[A-Z]

Letter or digit:

[A-Za-z0-9]

Whitespace:

[[:space:]]

Word characters:

[[:alnum:]_]

Wildcards

Any character:

.

Example:

sed '/c.t/p'

Matches:

cat
cot
cut

Quantifiers

Zero or more:

.*

One or more (with -E):

.+

Optional:

colou?r

Matches:

color
colour

Capture Groups

Suppose:

John Smith
Jane Brown

Swap first and last names.

Using -E:

sed -E 's/(.*) (.*)/\2, \1/'

Output:

Smith, John
Brown, Jane

Explanation:

(.*)   -> Group 1
(.*)   -> Group 2
 
\1     -> First group
\2     -> Second group

Another Example

Input:

name=tri

Command:

sed -E 's/(.*)=(.*)/key=\1 value=\2/'

Output:

key=name value=tri

Extract Part of a Line

Input:

Version: 2.3.1

Command:

sed -E 's/Version: ([0-9.]+)/\1/'

Output:

2.3.1

Reordering Fields

Input:

2026-07-06

Command:

sed -E 's/([0-9]{4})-([0-9]{2})-([0-9]{2})/\3\/\2\/\1/'

Output:

06/07/2026

Removing Duplicate Spaces

Input:

hello     world

Command:

sed -E 's/[[:space:]]+/ /g'

Output:

hello world

Real Sysadmin Examples

Comment out every Listen directive:

sed 's/^Listen/#Listen/'

Normalize whitespace:

sed -E 's/[[:space:]]+/ /g'

Convert:

user = root

into:

user=root
sed -E 's/[[:space:]]*=[[:space:]]*/=/'

Extract an IP address:

sed -nE 's/.*client=([0-9.]+).*/\1/p'

BRE vs ERE

Without -E:

sed 's/\(.*\)/[\1]/'

With -E:

sed -E 's/(.*)/[\1]/'

The second form is much easier to read.


Cheat Sheet

PatternMeaning
^Start of line
$End of line
.Any character
*Zero or more
+One or more (-E)
?Optional (-E)
(...)Capture group (-E)
\1, \2Captured text
[[:space:]]Whitespace
[[:digit:]]Digit

Key Takeaways

  • Prefer sed -E for new scripts; extended regex is cleaner.

  • Capture groups let you rearrange or extract parts of a line.

  • \1, \2, etc. refer to previously captured groups.

  • sed excels at transforming structured text such as logs and configuration files.