Python Editing Text Streams with sed
`sed` (Stream Editor) performs non-interactive text transformations on input streams or files. It is the premier Unix tool for search-and-replace, deleting matching line ranges, inserting boilerplate headers, and automating config updates.
"`sed` is like an automated assembly-line robotic arm: as each line of text moves past on the conveyor belt, `sed` inspects, modifies, replaces, or discards it."
Deep Dive: How It Works
Substitution Syntax: `s/pattern/replacement/flags` where `/g` replaces all occurrences on each line and `/i` ignores case.
In-Place Editing (-i): `sed -i` writes changes directly back to disk (on macOS: `sed -i ''`).
Alternative Delimiters: If patterns contain slashes (like URLs or filepaths), use `|` or `#` as delimiters: `sed 's|http://|https://|g'`.
Syntax Blueprint
sed 's/old/new/g' file.txt # Print replaced text to stdout sed -i 's/DEBUG/INFO/g' config.env # In-place file replacement sed '/^#/d' config.ini # Delete commented lines sed -n '5,10p' document.txt # Print only lines 5 to 10
Use sed for fast stream manipulation and automated configuration replacements.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Forgetting that macOS BSD sed requires an empty extension argument for `-i` (`sed -i ''`).Why it happens: BSD sed and GNU sed handle in-place backup arguments differently.
How to fix: In cross-platform scripts, write to a temporary file and mv, or detect OS.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Replace Words with sed
Echo "Hello World" into a pipe to `sed 's/World/ZenCompiler/g'`.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.