LAB-TEXT-04 - Stream Editing with sed
TXT Text Processing
Stream Editing with sed
Use sed to preview replacements, save safe in-place edits, and delete matching lines in a practice file.
40 min INTERMEDIATE LINUX Curriculum-reviewed
Prerequisites
Success criteria
- Use sed to preview replacements, save safe in-place edits, and delete matching lines in a practice file.
- Repeat the workflow without copy-paste or step-by-step prompting.
Safety notes
- Preview sed changes before using `-i`, and prefer `-i.bak` while you are still learning.
Part A: The Field Guide
What This Lab Is Really About
sed is useful when you need to make a repeatable text change without opening a text editor each time.
The important learning goal is not speed. It is confidence:
- preview the change
- understand what matched
- then save it safely
Command Reference
sed ‘s/debug/info/’ config.txt sed ‘s/debug/info/g’ config.txt sed -i.bak ‘s/debug/info/g’ config.txt sed ‘/DEBUG/d’ app.log
Part B: The Drill Deck
Terminal required: work only on practice files in a disposable folder.
G Guided Step by step - type exactly this and compare the result >
Exercise G1: Preview a Replacement
- Create a practice folder:
mkdir -p "$HOME/sed_lab"
cd "$HOME/sed_lab"- Create a file:
printf "mode=debug\nlog=debug\n" > config.txt- Preview a replacement without saving:
sed 's/debug/info/g' config.txt- Read the original file with
cat config.txtand confirm it has not changed yet.
Exercise G2: Save the Edit with a Backup
- Run:
sed -i.bak 's/debug/info/g' config.txt- Read the updated file:
cat config.txt- Confirm the backup exists:
lsExercise G3: Delete Matching Lines
- Create a small log file:
printf "INFO boot\nDEBUG warmup\nINFO ready\nDEBUG cache\n" > app.log- Remove debug lines in the output:
sed '/DEBUG/d' app.log- Confirm that only the non-debug lines are printed.
S Solo Task described, hints available - figure it out >
Exercise S1: Use a Different Delimiter
- Create a file containing a path:
echo "path=/usr/local/bin/python" > path.conf- Replace the path using
#as the sed delimiter:
sed 's#/usr/local/bin/python#/opt/python3/bin#g' path.conf- Confirm why a different delimiter is easier to read here than escaping every slash.
Exercise S2: Save the Path Change
- Make the previous change permanent with a backup:
sed -i.bak 's#/usr/local/bin/python#/opt/python3/bin#g' path.conf- Verify both the changed file and the backup.
M Mission Real scenario - no hints, combine multiple skills >
Mission M1: Patch a Practice Config File
Create a file named sshd_practice.conf with this content:
Port 22
X11Forwarding yes
PermitRootLogin noNow write one sed command that:
- makes a backup of the file
- changes
X11Forwarding yestoX11Forwarding no - keeps the rest of the file unchanged
Afterward, verify the result with grep X11Forwarding sshd_practice.conf.