Chapter 21: Bash Stream Editor (sed)

What is sed? (super simple first)

sed = stream editor It’s a tool that reads text line-by-line (from a file or from pipe), makes changes automatically, and prints the result (usually to screen or new file).

Think of it as:

  • Find-and-replace on steroids for the whole file/stream
  • A non-interactive editor (no opening vim/nano – it works in scripts & pipelines)
  • Perfect for: cleaning logs, updating configs, renaming variables in code, removing lines, adding headers/footers, etc.

Most people use sed for substitution (replace text), but it can also delete, insert, print selectively, and more.

Basic syntax (memorize this pattern)

Bash

The most common command is substitution:

Bash

1. Create a test file right now (copy-paste this)

Bash

2. Super basic examples (try these now!)

Bash

3. Very common options (you’ll use these daily)

Option What it does Example command Why useful?
-i Edit file in place (overwrite original) sed -i ‘s/old/new/g’ config.txt Update files directly
-i.bak Edit in place + make backup sed -i.bak ‘s/old/new/g’ file.txt Safe – keeps original as .bak
-e Multiple commands sed -e ‘s/a/b/’ -e ‘s/x/y/’ file.txt Chain changes
-r or -E Use extended regex (modern) sed -E 's/(old bad)/good/g' file.txt
-n Suppress auto-print (use with p) sed -n ‘/pattern/p’ file.txt Like grep
-f Read commands from script file sed -f changes.sed file.txt Complex scripts

4. Delete lines (very powerful)

Bash

5. Insert / Append lines

Bash

6. Change delimiter (when pattern has / )

Bash

7. Capture groups & backreferences (advanced but useful)

Bash

8. Real-world examples you will use daily

Bash

9. Quick cheat-sheet table

Goal Command example
Replace first match per line sed ‘s/old/new/’ file
Replace all matches sed ‘s/old/new/g’ file
Case insensitive sed ‘s/old/new/gi’ file
In-place edit + backup sed -i.bak ‘s/old/new/g’ file
Delete matching lines sed ‘/pattern/d’ file
Print only matching lines sed -n ‘/pattern/p’ file
Insert before line N sed ‘NiNew text’ file
Append after line N sed ‘NaNew text’ file
Use different delimiter `sed ‘s
Swap words with capture sed -E ‘s/(\w+) (\w+)/\2 \1/’ file

10. Pro tips from daily use

  • Always test without -i first → see output on screen
  • Use -i.bak until you’re 100% sure
  • Quote commands ‘…’ to protect from shell
  • For very complex → put in file: sed -f myscript.sed file
  • sed + pipes = power: cat log | grep error | sed ‘s/time=[0-9]*//’

Now open terminal and try these 3:

Bash

Tell me what you see! Or ask:

  • “How to replace only between quotes?”
  • “How to number only error lines in log?”
  • “Best sed for cleaning CSV files?”

We’ll build exact commands together! 😄

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *