sed Basics

sed is a stream editor. Its most common use: find and replace.

Basic Substitution

Terminal
$echo 'hello world' | sed 's/world/universe/'
hello universe

Syntax: s/pattern/replacement/

Replace in Files

Terminal
$sed 's/old/new/' file.txt
(outputs modified content)

This prints the result but doesn't modify the file.

Modify File In-Place

Terminal
$sed -i 's/old/new/' file.txt
(file is modified)

-i edits the file in place.

Backup First

-i is dangerous - no undo. Create a backup:

hljs bash
sed -i.bak 's/old/new/' file.txt

This creates file.txt.bak before modifying.

Replace All Occurrences

By default, sed replaces only the first match per line:

Terminal
$echo 'hello hello hello' | sed 's/hello/hi/'
hi hello hello
$echo 'hello hello hello' | sed 's/hello/hi/g'
hi hi hi

g = global (all occurrences).

Case-Insensitive

Terminal
$echo 'Hello HELLO hello' | sed 's/hello/hi/gi'
hi hi hi

i flag for case-insensitive.

Using Different Delimiters

When your pattern contains /, use a different delimiter:

Terminal
$echo '/usr/local/bin' | sed 's|/usr/local|/opt|'
/opt/bin

You can use |, #, @, or any character.

Delete Lines

Terminal
$sed '/pattern/d' file.txt
(lines with 'pattern' deleted)
$sed '5d' file.txt
(line 5 deleted)
$sed '1,10d' file.txt
(lines 1-10 deleted)
Terminal
$sed -n '5p' file.txt
(only line 5)
$sed -n '5,10p' file.txt
(lines 5-10)

-n suppresses default output, p prints.

Real-World Examples

Change Config Values

Terminal
$sed -i 's/port=8080/port=3000/' config.ini

Remove Comments

Terminal
$sed '/^#/d' config.txt
(removes lines starting with #)

Remove Empty Lines

Terminal
$sed '/^$/d' file.txt
(removes blank lines)

Add Prefix to Lines

Terminal
$sed 's/^/PREFIX: /' file.txt
(each line prefixed)

Replace in Multiple Files

Terminal
$sed -i 's/old/new/g' *.txt
(all .txt files modified)

Capture Groups

For complex replacements:

Terminal
$echo 'hello world' | sed 's/\(hello\) \(world\)/\2 \1/'
world hello

\(pattern\) captures, \1 references it.

Extended Regex

Use -E for easier regex syntax:

hljs bash
echo 'hello world' | sed -E 's/(hello) (world)/\2 \1/'
Knowledge Check

How do you replace ALL occurrences of 'old' with 'new' in a file?

Quick Reference

CommandEffect
s/old/new/Replace first occurrence
s/old/new/gReplace all occurrences
s/old/new/giReplace all, case-insensitive
-iEdit file in place
-i.bakBackup before editing
/pattern/dDelete matching lines
-n '5p'Print only line 5

Key Takeaways

  • sed 's/old/new/' replaces first occurrence per line
  • Add g for global replacement
  • -i edits in place (dangerous without backup!)
  • -i.bak creates backup before modifying
  • Use different delimiters when patterns contain /
  • sed '/pattern/d' deletes matching lines

Congratulations! You've completed Chapter 4: Text Manipulation.

Next chapter: Pipes and Redirection - the power of connecting commands.