1. SED and the Power of Replacement

The stream editor that rewrites text on the fly

Every Unix system ships with a tiny program called sed — the stream editor. It reads text one line at a time, applies a set of editing commands, and writes the result to standard output. No file is opened in a window, no cursor blinks on screen. sed does its work in a pipeline, silently transforming text as it flows through.

That sounds modest, but sed is one of the most powerful text-processing tools ever written. With a single line you can search-and-replace across thousands of files, reformat log output, strip HTML tags, or rewrite configuration on the fly.

Why SED?

Most people first meet sed through its substitute command:

Basic substitution

echo "hello world" | sed 's/world/planet/'

Output: hello planet

The s command is by far the most used feature, but it's only one of over twenty commands sed understands. Before we explore them, let's understand how sed actually processes text.

The Processing Model

sed works in a simple loop:

  1. Read the next line of input into a buffer called the pattern space
  2. Apply each command (in order) to the pattern space
  3. Print the pattern space to standard output (unless -n is set)
  4. Clear the pattern space and go back to step 1

This line-at-a-time model is what makes sed a stream editor — it never needs to load the entire file into memory.

The pattern space in action

# Input file: colors.txt
red
green
blue

Command: delete lines containing "green"

sed '/green/d' colors.txt

Output:

red
blue

The Substitute Command in Depth

The substitute command has this form:

s/pattern/replacement/flags
  • pattern — a regular expression to match
  • replacement — the text to insert in place of the match
  • flags — modifiers that change how substitution works

Common Flags

Flag Meaning
g Replace all matches on the line, not just the first
i Case-insensitive matching (GNU extension)
p Print the line if a substitution was made
w file Write the line to file if a substitution was made
2, 3... Replace only the nth match

Global vs. first match

echo "aaa bbb aaa" | sed 's/aaa/xxx/'
# xxx bbb aaa  (only the first match)

echo "aaa bbb aaa" | sed 's/aaa/xxx/g'

xxx bbb xxx (all matches)

Back-references

Parentheses in the pattern create capture groups. In the replacement, \1, \2, etc. refer back to what each group matched. The entire match is available as &.

Swapping two words

echo "first second" | sed 's/\(.*\) \(.*\)/\2 \1/'
# second first

Addresses — Targeting Specific Lines

By default, a sed command applies to every line. Addresses let you restrict which lines a command acts on.

Address Meaning
5 Line 5 only
$ The last line
/regex/ Lines matching the regex
1,10 Lines 1 through 10
1~2 Every odd-numbered line (GNU)
/start/,/end/ From the first line matching /start/ to the first line matching /end/

Delete blank lines

sed '/^$/d' file.txt

Replace only between markers

sed '/BEGIN/,/END/ s/old/new/g' config.txt

Beyond Substitution

sed has a handful of other commands worth knowing:

Command What it does
d Delete the pattern space (skip to next line)
p Print the pattern space
a\ text Append text after the current line
i\ text Insert text before the current line
c\ text Replace the current line with text
y/abc/xyz/ Transliterate characters (like tr)
q Quit immediately

The Hold Space

sed has a second buffer called the hold space. You can swap data between the pattern space and the hold space to do multi-line operations:

Command Effect
h Copy pattern space to hold space
H Append pattern space to hold space
g Copy hold space to pattern space
G Append hold space to pattern space
x Exchange pattern and hold spaces

This is what gives sed its surprising power — and its reputation for write-only one-liners.

Reverse the order of lines

# Tuck each line into the hold space, building in reverse
sed -n '1!G; h; $p' file.txt

Practical Recipes

Rename a variable across a codebase

# Replace all occurrences of "oldVar" with "newVar" in-place
sed -i 's/oldVar/newVar/g' src/*.js

Strip trailing whitespace

sed -i 's/[[:space:]]*$//' file.txt

Extract values from a log

# Print only lines containing "ERROR" and strip the timestamp
sed -n '/ERROR/ { s/^[^ ]* //; p; }' app.log

Comment out a block

sed '/DEBUG_START/,/DEBUG_END/ s/^/# /' script.sh

When to Use SED vs. Other Tools

Task Best tool
Simple find-and-replace sed
Column-based data awk
Complex multi-line transforms awk or a scripting language
Interactive editing vim, nano, etc.
JSON/XML/YAML transforms jq, xmlstarlet, yq

sed excels when you need a quick, scriptable, in-place text transformation. It's a scalpel, not a Swiss army knife — and that's exactly what makes it indispensable.

Summary

  • sed processes text one line at a time through a pattern space
  • The substitute command (s/pattern/replacement/flags) handles most use cases
  • Addresses let you target specific lines or ranges
  • Back-references (\1, &) capture and reuse matched text
  • The hold space enables multi-line tricks
  • For quick, scriptable text transforms in a pipeline, sed is hard to beat