Linux stream editing

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.txt

Replace globally per line

sed 's/old/new/g' file.txt

Print matching lines

sed -n '/error/p' error_log

In-place edit

sed -i.bak 's/old/new/g' file.txt

Replace text

TaskCommand
First match per linesed 's/http:/https:/' file.txt
Every match per linesed 's/http:/https:/g' file.txt
Case-insensitive replacesed 's/error/warning/Ig' file.txt
Use another delimitersed 's#/old/path#/new/path#g' file.txt
Replace only on matching linessed '/example.com/s/http:/https:/g' file.txt

Edit 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
CommandUse
sed 's/old/new/g' filePreview only.
sed -i.bak 's/old/new/g' fileEdit file and create backup.
sed -i 's/old/new/g' fileEdit file without backup. Use carefully.

Regex examples

PatternExample
Start of linesed 's/^/# /' file.txt
End of linesed 's/$/;/' file.txt
Capture groupsed -E 's/(user=)[^ ]+/\1hidden/g' file.txt
Multiple spacessed -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.txt

Remove trailing whitespace

sed -i.bak 's/[[:space:]]*$//' file.txt

Change PHP memory limit

sed -i.bak 's/memory_limit = .*/memory_limit = 256M/' php.ini

Show config block

sed -n '/BEGIN BLOCK/,/END BLOCK/p' config.txt
Real workflows

sed workflows for safe text changes

Preview a replacement

sed 's/old-domain.com/new-domain.com/g' config.txt

Edit with backup

sed -i.bak 's/http:/https:/g' file.txt

Print a line range

sed -n '20,40p' app.log

Delete blank lines

sed '/^$/d' file.txt
Use a backup suffix with -i when changing files you care about.
FAQ

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.