sed Operations Reference
1. Overview
sed (stream editor) performs text transformations on input streams. Essential for configuration file modifications, log parsing, and automation scripts.
|
Golden Rule: Preview before apply. Always use |
2. Core Concepts
4. Preview vs Apply Pattern
|
This is critical. Never run |
4.1. Step 1: Preview (see what will change)
sed -n 's/old-value/new-value/gp' /path/to/file
-
-nsuppresses normal output -
pflag prints only lines that matched/changed -
File is NOT modified
sed -n 's/dc-01\.inside\.domusdigitalis\.dev/home-dc01.inside.domusdigitalis.dev/gp' /etc/krb5.conf
kdc = home-dc01.inside.domusdigitalis.dev
admin_server = home-dc01.inside.domusdigitalis.dev
5. Escaping Special Characters
5.1. Characters That Need Escaping
In basic regex (BRE), escape these:
| Character | Escape As |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# WRONG - dots match any character
sed -n 's/dc-01.inside.domusdigitalis.dev/new/gp' file
# CORRECT - dots are literal
sed -n 's/dc-01\.inside\.domusdigitalis\.dev/new/gp' file
6. Address Ranges
7. Common Operations
7.1. Delete Lines
# Delete lines containing pattern
sed '/pattern/d' file
# Delete empty lines
sed '/^$/d' file
# Delete lines 1-5
sed '1,5d' file
# Delete last line
sed '$d' file
8. Real-World Examples
8.1. Configuration File Updates
# Preview
sed -n 's/dc-01\.inside\.domusdigitalis\.dev/home-dc01.inside.domusdigitalis.dev/gp' /etc/krb5.conf
# Apply
sudo sed -i 's/dc-01\.inside\.domusdigitalis\.dev/home-dc01.inside.domusdigitalis.dev/g' /etc/krb5.conf
# Preview
sed -n 's/10\.50\.1\.50/10.50.1.51/gp' /etc/hosts
# Apply
sudo sed -i 's/10\.50\.1\.50/10.50.1.51/g' /etc/hosts
8.2. Comment/Uncomment Lines
# Comment out a line (add # at start)
sed -i 's/^PasswordAuthentication yes/#PasswordAuthentication yes/' /etc/ssh/sshd_config
# Uncomment a line (remove # at start)
sed -i 's/^#PasswordAuthentication yes/PasswordAuthentication yes/' /etc/ssh/sshd_config
# Comment all lines matching pattern
sed -i '/pattern/s/^/#/' file
10. Troubleshooting
11. Quick Reference
| Operation | Command |
|---|---|
Preview substitution |
|
Apply substitution |
|
Apply with backup |
|
Delete matching lines |
|
Delete empty lines |
|
Print matching lines |
|
Print line range |
|
Comment line |
|
Replace in place (global) |
|
Multiple substitutions |
|