← Back to Bash Course | Chapter 10: Text Processing Tools | Lesson 3 of 12

sed Basics

sed reads text line by line and applies simple edits, most commonly finding and replacing pieces of text.

Basic Substitution

The s/old/new/ command substitutes the first match of old with new on each line. Without a trailing g flag, only the first occurrence per line is replaced.

Example: Basic Substitution

bash
#!/bin/bash
echo "cat sat on the cat mat" | sed 's/cat/dog/'

Global Substitution

Adding a g flag after the third slash makes the substitution apply to every match on the line, not just the first one found.

Example: Global Substitution

bash
#!/bin/bash
echo "cat sat on the cat mat" | sed 's/cat/dog/g'

Editing a File in Place

sed -i 's/old/new/' file rewrites the file itself instead of printing the change to stdout. This is destructive, so it is worth testing the plain (non -i) version on a sample first.

Warning: sed -i overwrites the file with no confirmation; keep a backup or use version control before running it on important files.

Example: Editing a File in Place

bash
#!/bin/bash
echo "version=1.0" > config.txt
sed -i 's/1.0/2.0/' config.txt
cat config.txt
rm -f config.txt

Deleting Lines

sed Nd deletes line number N. sed '/pattern/d' deletes every line matching pattern anywhere in the line, which is a quick way to strip comments or blank lines.

Example: Deleting Lines

bash
#!/bin/bash
printf "keep\n# comment\nkeep too\n# another comment\n" > notes.txt
sed '/^#/d' notes.txt
rm -f notes.txt
Common Mistakes
  1. Forgetting sed prints to stdout by default and does not modify the file unless -i is used.
  2. Using sed -i on macOS/BSD sed without an argument and hitting an error, since GNU sed and BSD sed have different -i syntax; on GNU/Linux (like this course's sandbox) -i takes no separate backup suffix unless one is given.
  3. Not escaping special regex characters like . or / in the pattern, causing sed to match more (or less) than intended.
Chapter Summary
  • sed 's/old/new/' file replaces the first occurrence of old with new on each line.
  • Adding a g flag (s/old/new/g) replaces every occurrence on each line, not just the first.
  • sed -i edits a file in place instead of printing the result to stdout.
  • sed 2d file deletes line 2; sed '/pattern/d' file deletes every line matching a pattern.
🔒

Chapter Quiz — Complete all 12 topics to unlock

0/12 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.