Editing streams with sed
Quick answer
sed applies editing rules to a stream of text. It can replace labels, select lines or omit records without opening an interactive editor. By default it writes the result to standard output, not back into the input file.
Prepare the practice environment
Use the chapter fixture described in lab-fixtures/search-transform/README.md. Run setup as a normal user in a disposable Linux environment, enter the printed directory and check pwd. Every example assumes a fresh fixture. Commands omit the terminal prompt; outputs below are not commands.
How it works
The substitution s/pattern/replacement/ replaces the first match per line; g replaces all nonoverlapping matches on that line. A numeric address selects a line, and -n suppresses automatic printing so p prints only selected records. In a replacement, & means the whole match. sed uses BRE by default; -E enables ERE. GNU -i changes files in place; BSD variants differ. Prefer a new output file and review it first.
If a line contains red twice, the default substitution changes the first match only; adding g changes both nonoverlapping matches. This decision repeats independently for every line. A normal sed command writes a transformed stream and leaves the input file unchanged. Never redirect the result back to that same input path with >: the shell can truncate it before sed reads it.
Try the examples
Only the displayed stream changes.
Expected stdout:
INFO startWARN disk fullINFO checkWARN retryThe g flag replaces both red values on the first line.
Expected stdout:
blue blue greenblueAutomatic output is off; p prints lines 2 through 3.
Expected stdout:
ERROR disk fullINFO checkCommon mistakes
Never redirect sed output to the same input filename: the shell can truncate the file before sed reads it. Avoid -i until a reviewed backup and restore plan exists.
Practice
Write the transformed log to preview.log using >, then compare it to events.log visually using cat. Verify that events.log still contains ERROR.
Related references
Study: sed. These are reference names, not deployed links.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Editing streams with sed — Knowledge Check
Apply the lesson concepts to the controlled text fixture.
What does sed do by default?
What does g mean in s/red/blue/g?
Why use -n with p?
Which destination is safest for a preview?