Mission 9 of 30
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.
Your outcome: You can automate small edits without fearing accidental irreversible changes.
Practice inside
Practice inside
~/linux-practice. Check your setup before you begin.
Prerequisite: Grep: Search Master
.
What you’ll practice
- Use sed substitution
- Address lines
- Use backup files for in-place edits
The mental model
- sed reads text, applies editing rules, and prints results.
- Test without -i first.
- If editing in place, prefer -i.bak while learning.
Try it in your terminal
Substitute safely
Safe in practice folderPrints changed output without modifying the file.
Run from ~/linux-practice
cd ~/linux-practice
echo -e 'Hello\nWorld\nHello World' > text.txt
sed 's/Hello/Hi/' text.txt
sed 's/Hello/Hi/g' text.txt Print selected lines
Safe in practice folderShows only selected lines.
Run from ~/linux-practice
sed -n '2p' text.txt
sed -n '1,2p' text.txt In-place with backup
CautionChanges the file and keeps a backup copy.
Run from ~/linux-practice
sed -i.bak 's/Hello/Hi/g' text.txt
cat text.txt
cat text.txt.bak Put it into practice
- Replace apple with orange in a practice file.
- Verify the .bak backup exists.
Check your result
The preview is correct and the original still has a backup.
Common mistakes
- You run `sed -i 's/foo/bar/' file.txt` and realize too late that your pattern was wrong. The file is now changed. No backup, no undo. Always run the command without `-i` first. See the output. Then add `-i.bak` — it keeps a backup file so you can recover if things go sideways.
- You type `sed 's/Hello/Hi/' file.txt` and notice only the first 'Hello' on each line changed. That's the default behavior — sed replaces only the first match per line. Add the `g` flag at the end for 'global': `sed 's/Hello/Hi/g'`. The `g` stands for global, and it catches every match on the line.
Check your understanding
Explain these in your own words. If you’re unsure, revisit the examples before moving on.
- What does the g flag do?
- Why is -i.bak safer than -i?
Your practice, your pace
Loading saved progress…