The sed (stream editor) command is a powerful text processing utility that performs basic text transformations on an input stream (a file or input from a pipeline). Unlike interactive text editors, sed processes text in a single pass, making it extremely efficient for automated text manipulation tasks. It's one of the fundamental tools in Unix/Linux text processing alongside grep and awk.
Key Capabilities:
Search and replace text using regular expressions
Delete lines matching specific patterns
Insert and append text at specific locations
Transform text (transliteration)
Print specific lines or ranges
Modify files in-place or output to streams
Note: sed is part of the GNU coreutils and is available on all Linux/Unix systems by default. It uses regular expressions (regex) for pattern matching, similar to grep and awk.
Command Syntax
sed [OPTIONS] 'command' file(s)
sed [OPTIONS] -e 'command1' -e 'command2' file(s)
sed [OPTIONS] -f script.sed file(s)
Common Options
Option
Description
-n
Suppress automatic output (quiet mode)
-e
Add script command (allows multiple commands)
-f
Read commands from file
-i
Edit files in-place (modify original file)
-i.bak
Edit in-place and create backup with .bak extension
-r or -E
Use extended regular expressions
--version
Display version information
Basic sed Commands
Command
Description
Example
s/pattern/replacement/
Substitute (replace) text
s/old/new/
d
Delete lines
/pattern/d
p
Print lines
/pattern/p
a
Append text after line
/pattern/a\text
i
Insert text before line
/pattern/i\text
c
Change (replace) entire line
/pattern/c\text
y/src/dst/
Transliterate (character substitution)
y/abc/ABC/
Detailed Examples
Example 1: Basic Search and Replace
echo "Hello World" | sed 's/World/Universe/'
Hello Universe
The most basic sed operation: substitute (replace) text. The syntax is s/pattern/replacement/:
s - substitute command
/World/ - pattern to search for
/Universe/ - replacement text
By default, replaces only the first occurrence per line
This is the most commonly used sed operation, essential for text transformations in scripts.
Tip: You can use any delimiter instead of /, such as s|World|Universe| or s#World#Universe#. This is useful when your pattern contains slashes (like file paths).
Example 2: Global Replace (All Occurrences)
echo "The cat in the hat sat on the mat" | sed 's/at/AT/g'
The cAT in the hAT sAT on the mAT
The g flag (global) replaces all occurrences on each line, not just the first:
Without g: only first match per line is replaced
With g: all matches on line are replaced
Essential for comprehensive text transformations
Compare without g: sed 's/at/AT/' would output "The cAT in the hat sat on the mat"
# Reverse file (print lines in reverse order)
sed '1!G;h;$!d' file.txt
# Remove duplicate consecutive lines
sed '$!N; /^\(.*\)\n\1$/!P; D' file.txt
sed maintains two buffers: pattern space (current line) and hold space (temporary storage). Advanced sed users leverage these for complex transformations like reversing files or removing duplicates.
Technique 2: Conditional Execution
# Apply substitution only if line contains pattern
sed '/ERROR/s/^/*** /' logfile.txt
# Apply substitution if line does NOT contain pattern
sed '/SUCCESS/!s/^/[FAILED] /' results.txt
Technique 3: Multi-line Processing
# Join lines ending with backslash
sed -e :a -e '/\\$/N; s/\\\n//; ta' file.txt
# Replace newlines with spaces (entire file on one line)
sed ':a;N;$!ba;s/\n/ /g' file.txt
Performance Considerations
Performance Tips:
sed processes files sequentially and is very efficient
For simple substitutions, sed is faster than most scripting languages
Use specific patterns instead of .* when possible
Combine multiple operations in one sed invocation
For very large files, consider GNU parallel with sed
Common Pitfalls and Solutions
Pitfall 1: Special Characters in Patterns
# Problem: Trying to replace dots (matches any character)
sed 's/192.168.1.1/10.0.0.1/' file.txt # WRONG
# Solution: Escape special characters
sed 's/192\.168\.1\.1/10.0.0.1/' file.txt # CORRECT
Pitfall 2: Greedy Matching
# Problem: Removing HTML tags removes too much
echo "<b>Hello</b> <i>World</i>" | sed 's/<.*>//'
# Output: (empty - matched from first < to last >)
# Solution: Use non-greedy pattern
echo "<b>Hello</b> <i>World</i>" | sed 's/<[^>]*>//g'
# Output: Hello World
Pitfall 3: In-Place Editing Without Backup
Never do this in production:
sed -i 's/old/new/g' critical_config.conf # Dangerous!
Always create backups:
sed -i.backup 's/old/new/g' critical_config.conf # Safe
Troubleshooting
Testing sed Commands Safely
# Always test without -i first
sed 's/old/new/g' file.txt | less
# Create a test file
cp important.conf test.conf
sed -i 's/old/new/g' test.conf
diff important.conf test.conf
# Use -i with backup
sed -i.bak 's/old/new/g' important.conf
diff important.conf important.conf.bak
sed vs. Other Tools
Task
sed
Alternative
Simple search/replace
✅ Best choice
awk, perl
Pattern matching only
❌ Use grep
grep (faster, simpler)
Column/field processing
❌ Use awk
awk (more powerful)
Complex logic
❌ Use scripting language
Python, Perl
In-place file editing
✅ Excellent
perl -i, Python
Stream processing
✅ Perfect
awk, Perl
Related Commands
grep - Search text for patterns
awk - Pattern scanning and processing language
tr - Translate or delete characters
cut - Remove sections from lines
paste - Merge lines of files
sort - Sort lines of text
uniq - Remove duplicate lines
perl - Practical Extraction and Report Language
vim - Text editor with sed-like commands (ex mode)
ed - Line-oriented text editor (sed's ancestor)
Quick Reference Card
Most Common sed Commands
# Basic substitution
sed 's/old/new/' file.txt
# Global substitution
sed 's/old/new/g' file.txt
# In-place editing with backup
sed -i.bak 's/old/new/g' file.txt
# Delete lines matching pattern
sed '/pattern/d' file.txt
# Print specific lines
sed -n '10,20p' file.txt
# Multiple commands
sed -e 's/a/A/' -e 's/b/B/' file.txt