Suggested day 920–30 minutesCaution

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.

Outcome: You can automate small edits without fearing accidental irreversible changes.

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

1

Substitute safely

Safe

Prints changed output without modifying the file.

Terminal
cd ~/linux-practice
echo -e 'Hello\nWorld\nHello World' > text.txt
sed 's/Hello/Hi/' text.txt
sed 's/Hello/Hi/g' text.txt
2

Print selected lines

Safe

Shows only selected lines.

Terminal
sed -n '2p' text.txt
sed -n '1,2p' text.txt
3

In-place with backup

Caution

Changes the file and keeps a backup copy.

Terminal
sed -i.bak 's/Hello/Hi/g' text.txt
cat text.txt
cat text.txt.bak

Checkpoint

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?

Shortcuts:Alt + ← previous lessonAlt + → next lessonAlt + H home? focus search