Sed Command Cheat Sheet
Use sed for quick stream editing: replace text, delete lines, print ranges, preview changes and safely edit files in place.
Syntax
Basic replacement
sed 's/old/new/' file.txtReplace globally per line
sed 's/old/new/g' file.txtPrint matching lines
sed -n '/error/p' error_logIn-place edit
sed -i.bak 's/old/new/g' file.txtReplace text
| Task | Command |
|---|---|
| First match per line | sed 's/http:/https:/' file.txt |
| Every match per line | sed 's/http:/https:/g' file.txt |
| Case-insensitive replace | sed 's/error/warning/Ig' file.txt |
| Use another delimiter | sed 's#/old/path#/new/path#g' file.txt |
| Replace only on matching lines | sed '/example.com/s/http:/https:/g' file.txt |
Print and delete lines
Print line range
sed -n '10,20p' file.txtPrint matching lines
sed -n '/Fatal error/p' error_logDelete blank lines
sed '/^$/d' file.txtDelete comments
sed '/^#/d' config.confEdit files safely
Use backups: when editing in place, use
-i.bak first. That gives you a rollback file.sed -i.bak 's/old-domain.com/new-domain.com/g' config.php
diff -u config.php.bak config.php
| Command | Use |
|---|---|
sed 's/old/new/g' file | Preview only. |
sed -i.bak 's/old/new/g' file | Edit file and create backup. |
sed -i 's/old/new/g' file | Edit file without backup. Use carefully. |
Regex examples
| Pattern | Example |
|---|---|
| Start of line | sed 's/^/# /' file.txt |
| End of line | sed 's/$/;/' file.txt |
| Capture group | sed -E 's/(user=)[^ ]+/\1hidden/g' file.txt |
| Multiple spaces | sed -E 's/[[:space:]]+/ /g' file.txt |
Practical recipes
Mask email addresses
sed -E 's/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+/[email hidden]/g' file.txtRemove trailing whitespace
sed -i.bak 's/[[:space:]]*$//' file.txtChange PHP memory limit
sed -i.bak 's/memory_limit = .*/memory_limit = 256M/' php.iniShow config block
sed -n '/BEGIN BLOCK/,/END BLOCK/p' config.txtsed workflows for safe text changes
Preview a replacement
sed 's/old-domain.com/new-domain.com/g' config.txtEdit with backup
sed -i.bak 's/http:/https:/g' file.txtPrint a line range
sed -n '20,40p' app.logDelete blank lines
sed '/^$/d' file.txtUse a backup suffix with
-i when changing files you care about.Frequently Asked Questions
What is sed used for?
sed is used to transform text streams, commonly for replacements, deleting lines and printing ranges.
How do I replace text with sed?
Use sed 's/old/new/g' file.
How do I edit a file in place with sed?
Use sed -i, preferably with a backup suffix such as sed -i.bak.
How do I print specific lines with sed?
Use sed -n 'START,ENDp' file.