Mission 4 of 5
Sed: Stream Editing Safely
Preview and apply a safe text correction with a backup.
Transform text with sed while learning a safer backup-first approach to in-place edits.
Mental model
Understand what is happening
sed reads text, applies editing rules, and prints results.
Test without -i first.
If editing in place, prefer -i.bak while learning.
Guided lab
Work through the mission
Substitute safely
Prints changed output without modifying the file.
cd ~/linux-practice
echo -e 'Hello\nWorld\nHello World' > text.txt
sed 's/Hello/Hi/' text.txt
sed 's/Hello/Hi/g' text.txtPrint selected lines
Shows only selected lines.
sed -n '2p' text.txt
sed -n '1,2p' text.txtIn-place with backup
Changes the file and keeps a backup copy.
sed -i.bak 's/Hello/Hi/g' text.txt
cat text.txt
cat text.txt.bakCheckpoint
Verify the mission
The preview is correct and the original still has a backup.
Try it yourself
One step without a recipe
Replace apple with orange in a practice file. Verify the .bak backup exists.
Need a hint?
Never use `sed -i` until you've seen the output without it. Run `sed 's/old/new/' file.txt` first. Read the output. If it looks right, then add `-i.bak` to save the change with a backup. I treat `-i` like a power drill — useful, but I don't reach for it before measuring twice.
Explain it back
Before you move on
- What does the g flag do?
- Why is -i.bak safer than -i?