sed Command Guide for Editing Text
This guide helps you understand and use the sed (stream editor) command, the classic tool for finding and replacing text without opening an editor.
What is sed, and Why Use It?
The sed command reads text line by line and applies editing instructions to each line — most commonly finding and replacing text, but also deleting lines, inserting new ones, and transforming entire streams. The standard way to change text in a file, especially in scripts.
Why Learn sed?
- Batch edits: Fix the same string in a hundred files with one command instead of a hundred editor sessions.
- Scripts need it: Shell scripts can’t open an interactive editor;
seddoes the same job silently. - Quick one-off fixes: Change a config value in place without learning a full language.
- It’s non-interactive: Perfect for cron jobs, deployment scripts, and pipelines.
sedis the difference between “I’ll edit this by hand” and “the script already did it.”
1. The Basic Substitution
The core command is s (substitute), in the form s/old/new/:
sed 's/foo/bar/' file.txt
- Replaces the first
fooon each line withbar, and prints the result. - The original file is not changed —
sedwrites to stdout by default.
Example:
echo "the cat sat" | sed 's/cat/dog/'
the dog sat
2. Replace All Occurrences and Use a Flag
To replace every occurrence on a line, add the g (global) flag:
sed 's/foo/bar/g' file.txt
To edit the file itself, use -i (in-place) — note this rewrites the file directly:
sed -i 's/foo/bar/g' file.txt
Safer in-place form — keep a backup of the original:
sed -i.bak 's/foo/bar/g' file.txt
- Creates
file.txt.bakbefore editing. Essential habit when editing important files.
3. Replace Only the First Match Per Line, or Specific Lines
sed '2s/foo/bar/' file.txt
- Edits only line 2. Line addresses can be a number (
5), a range (2,7), or a pattern (/error/).
sed '/^#/d' file.txt
- Deletes every line starting with
#(d= delete).
sed -n '10,20p' file.txt
-nsuppresses automatic printing;pprints only lines 10–20. This issedas a page selector.
4. Anchor Patterns to Start and End
Patterns can be anchored like regex:
sed 's/^//; s/$//' file.txt # remove leading and trailing empty matches (illustrative)
sed 's/^foo/bar/' file.txt # 'foo' only at the start of the line
sed 's/foo$/bar/' file.txt # 'foo' only at the end of the line
^= start of line,$= end of line.
Example — strip a prefix from every line:
sed 's/^WARN: //' app.log
5. Delete, Insert, and Append Lines
Beyond substitution, sed can restructure text:
sed '/blank-lines-pattern/d' file.txt # delete matching lines
sed 'i\Inserted before line 1' file.txt # insert text before the first line
sed 'a\Appended after line 1' file.txt # append text after the first line
sed 'c\Replaced the whole line' file.txt # replace the line entirely
Practical example — comment out every fstab entry for the CD-ROM:
sed -i '/cdrom/s/^/#/' /etc/fstab
6. Use Variables and Capture Groups
You can capture parts of a match with parentheses (-E for extended regex) and reuse them with \1, \2, …:
sed -E 's/([0-9]+)-([0-9]+)/\2-\1/' file.txt
That swaps the two numbers on each line. Variables work through the shell if you use double quotes:
name="alice"
sed "s/user:.*/user: $name/" /etc/passwd
- Single quotes keep
$literal; double quotes let the shell expand it.
7. Multi-Line Ranges and Scripts
sed programs can span multiple commands separated by ; or newlines:
sed -e 's/foo/bar/g' -e 's/baz/qux/g' file.txt
- Multiple
-eexpressions apply in order to every line.
A common range operation — print the block between two markers:
sed -n '/BEGIN/,/END/p' config.txt
8. sed vs. an Editor
| Task | sed | Editor |
|---|---|---|
| One-off change to a known string | ✅ Perfect | Fine |
| Same change in 100 files | ✅ One command | Painful |
| Complex restructuring | Awkward | ✅ Easier |
| Inside a shell script | ✅ Designed for it | ❌ Not possible |
Common Pitfalls
- Forgetting that
sedprints to stdout by default. Without-i, your file is untouched. sed -iwithout a backup. A bad pattern silently corrupts the file. Usesed -i.bakuntil you’re confident.- Quotes matter. Single quotes keep patterns literal; double quotes let the shell expand
$var— pick deliberately. s/foo/bar/only replaces the first occurrence per line. Addgfor all of them.- macOS
sedis BSD sed.sed -ineeds an argument (sed -i '') on macOS; GNU and BSD versions differ in subtle ways.
Related Pages
| Page | Relationship |
|---|---|
grep | Finds lines matching a pattern; sed uses the same pattern language for edits. |
awk | The other stream editor — better for columnar data and logic. |
tr | Character-level translation, a simpler cousin of sed. |
scripting.md | Where sed earns its keep: inside scripts. |
sed Cheatsheet
| Command | What It Does |
|---|---|
sed 's/old/new/' f | Replace first old per line, print result. |
sed 's/old/new/g' f | Replace all old per line. |
sed -i 's/old/new/g' f | Edit the file in place. |
sed -i.bak 's/x/y/' f | In-place with a backup file. |
sed -n '5p' f | Print only line 5. |
sed -n '10,20p' f | Print lines 10–20. |
sed '/pat/d' f | Delete lines matching pat. |
sed '/pat/s/^/#/' f | Comment out lines matching pat. |
sed -E 's/(a)(b)/\2\1/' f | Swap captured groups. |
sed -e 's/a/b/' -e 's/c/d/' f | Chain multiple edits. |
sed -n '/start/,/end/p' f | Print the block between two markers. |