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.

40–50 min Week 2 · Search, text, permissions, processes Ubuntu terminal
Your outcome: You can automate small edits without fearing accidental irreversible changes.
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 folder

Prints 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 folder

Shows only selected lines.

Run from ~/linux-practice

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

In-place with backup

Caution

Changes 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

  1. Replace apple with orange in a practice file.
  2. 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.

  1. What does the g flag do?
  2. Why is -i.bak safer than -i?

Your practice, your pace

Loading saved progress…

Discussion

Continue the conversation about this guide. Loading comments connects to GitHub Discussions through giscus.

Open community discussions on GitHub

Check before you copy

This command needs care. Read its context, confirm the target and location, and keep a recovery path.

Copying does not run a command.