Skip to content
LangStop
The Linux sed Command: Stream Editing Reality

The Linux sed Command: Stream Editing Reality

2 min read
Last updated:

The Linux sed Command: Stream Editing Reality

I needed to replace "localhost" with "production-db" in 500 configuration files across 50 servers. "Just use sed," they said. Two hours later, I had done it manually—sed's in-place editing scared me.

Let me share what I learned about sed—safely.


First sed Commands

Replace first occurrence

sed 's/old/new/' file.txt

Replace first "old" with "new" in each line.

Replace all occurrences

sed 's/old/new/g' file.txt

Replace every occurrence (global).

In-place edit

sed -i 's/old/new/g' file.txt

-i = in-place. DANGEROUS—backup first!

Backup before in-place

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

Creates file.txt.bak.


sed Address Ranges

Line numbers

sed '1,5 s/old/new/' file.txt

Only lines 1-5.

Pattern range

sed '/start/,/end s/old/new/' file.txt

From /start/ to /end/.

Every nth line

sed '1~2 s/old/new/' file.txt

Every other line.


sed Commands That Work

Print lines 10-20

sed -n '10,20p' file.txt

-n suppresses default output.

Delete lines 1-5

sed '1,5d' file.txt

Delete first 5 lines.

Delete blank lines

sed '/^$/d' file.txt

Delete empty lines.

Delete comments

sed '/^#/d' file.txt

Delete comment lines.

Insert line before

sed '1i\new line' file.txt

Insert at beginning.

Append line after

sed '$a\last line' file.txt

Append at end.

Print with line numbers

sed '=' file.txt | paste - - 

sed Flags Reference

Flag Meaning
g Global (all)
p Print
d Delete
i Insert before
a Append after
w Write to file

The sed Command Builder

Building sed commands—the sed Command Builder:

  • Pattern builder with test preview
  • In-place vs stdout clearly shown
  • Safety warnings

Safety Rules

  1. Always use -i.bak — have a backup.

  2. Test with stdout first — remove the -i.

  3. Use absolute paths — avoid mistakes.

  4. Escape special chars — ., /, etc.

  5. Check line numbers — before range edits.


Common sed Patterns

Replace in specific files

find . -name "*.conf" -exec sed -i.bak 's/old/new/g' {} \;

Replace across servers

ansible all -m shell -a "sed -i.bak 's/old/new/g' file.txt"

Conditional replace

sed '/pattern/s/old/new/g' file.txt

Replace only in matching lines.


Lessons Learned

  1. Use -i.bak — safety first.

  2. Test without -i — see output first.

  3. Escape special characters — in patterns.

  4. sed is line-oriented — works line by line.

  5. Use awk for complex — sed is for simple.


Conclusion: sed Is Powerful

sed is stream editor—fast for simple replacements across many files.

The sed Command Builder makes building sed easy.


Further Reading

Explore Our Toolset