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
cutQuantifiers
Zero or more:
.*One or more (with -E):
.+Optional:
colou?rMatches:
color
colourCapture Groups
Suppose:
John Smith
Jane BrownSwap first and last names.
Using -E:
sed -E 's/(.*) (.*)/\2, \1/'Output:
Smith, John
Brown, JaneExplanation:
(.*) -> Group 1
(.*) -> Group 2
\1 -> First group
\2 -> Second groupAnother Example
Input:
name=triCommand:
sed -E 's/(.*)=(.*)/key=\1 value=\2/'Output:
key=name value=triExtract Part of a Line
Input:
Version: 2.3.1Command:
sed -E 's/Version: ([0-9.]+)/\1/'Output:
2.3.1Reordering Fields
Input:
2026-07-06Command:
sed -E 's/([0-9]{4})-([0-9]{2})-([0-9]{2})/\3\/\2\/\1/'Output:
06/07/2026Removing Duplicate Spaces
Input:
hello worldCommand:
sed -E 's/[[:space:]]+/ /g'Output:
hello worldReal Sysadmin Examples
Comment out every Listen directive:
sed 's/^Listen/#Listen/'Normalize whitespace:
sed -E 's/[[:space:]]+/ /g'Convert:
user = rootinto:
user=rootsed -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
| Pattern | Meaning |
|---|---|
^ | Start of line |
$ | End of line |
. | Any character |
* | Zero or more |
+ | One or more (-E) |
? | Optional (-E) |
(...) | Capture group (-E) |
\1, \2 | Captured text |
[[:space:]] | Whitespace |
[[:digit:]] | Digit |
Key Takeaways
-
Prefer
sed -Efor 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. -
sedexcels at transforming structured text such as logs and configuration files.