Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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; sed does 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.

sed is 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 foo on each line with bar, and prints the result.
  • The original file is not changed — sed writes 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.bak before 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
  • -n suppresses automatic printing; p prints only lines 10–20. This is sed as 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 -e expressions 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

TasksedEditor
One-off change to a known string✅ PerfectFine
Same change in 100 files✅ One commandPainful
Complex restructuringAwkward✅ Easier
Inside a shell script✅ Designed for it❌ Not possible

Common Pitfalls

  • Forgetting that sed prints to stdout by default. Without -i, your file is untouched.
  • sed -i without a backup. A bad pattern silently corrupts the file. Use sed -i.bak until 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. Add g for all of them.
  • macOS sed is BSD sed. sed -i needs an argument (sed -i '') on macOS; GNU and BSD versions differ in subtle ways.

PageRelationship
grepFinds lines matching a pattern; sed uses the same pattern language for edits.
awkThe other stream editor — better for columnar data and logic.
trCharacter-level translation, a simpler cousin of sed.
scripting.mdWhere sed earns its keep: inside scripts.

sed Cheatsheet

CommandWhat It Does
sed 's/old/new/' fReplace first old per line, print result.
sed 's/old/new/g' fReplace all old per line.
sed -i 's/old/new/g' fEdit the file in place.
sed -i.bak 's/x/y/' fIn-place with a backup file.
sed -n '5p' fPrint only line 5.
sed -n '10,20p' fPrint lines 10–20.
sed '/pat/d' fDelete lines matching pat.
sed '/pat/s/^/#/' fComment out lines matching pat.
sed -E 's/(a)(b)/\2\1/' fSwap captured groups.
sed -e 's/a/b/' -e 's/c/d/' fChain multiple edits.
sed -n '/start/,/end/p' fPrint the block between two markers.