sed
Overview
The sed
(Stream Editor) command is used to perform basic text transformations on an input stream. It’s a powerful tool for parsing and transforming text using regular expressions.
Syntax
sed [options] 'command' [input-file]
Common Options
Option | Description |
---|---|
-n |
Suppress output |
-e script |
Add script |
-f file |
Add script file |
-i |
Edit files in place |
-r |
Extended regex |
-E |
Extended regex |
-s |
Separate files |
-l N |
Line length |
--debug |
Debug info |
--help |
Show help |
--version |
Show version |
Common Commands
Command | Description |
---|---|
p |
Print line |
d |
Delete line |
s/pat/rep/ |
Substitute |
y/pat/rep/ |
Transform chars |
i |
Insert text |
a |
Append text |
c |
Change line |
q |
Quit |
r file |
Read file |
w file |
Write to file |
Key Use Cases
- Text substitution
- Line filtering
- Text transformation
- File editing
- Data extraction
Examples with Explanations
Example 1: Basic Substitution
sed 's/old/new/' file
Replace first occurrence
Example 2: Global Substitution
sed 's/old/new/g' file
Replace all occurrences
Example 3: Delete Lines
sed '/pattern/d' file
Delete matching lines
Common Usage Patterns
Multiple commands:
sed -e 's/a/b/' -e 's/x/y/'
In-place edit:
sed -i 's/old/new/g' file
Line range:
sed '1,5s/old/new/' file
Security Considerations
- File permissions
- Backup files
- Regular expressions
- Input validation
- Command injection
Additional Resources
Best Practices
- Test commands
- Use backups
- Quote patterns
- Document changes
- Verify results
Regular Expressions
- Basic regex
- Extended regex
- Back references
- Character classes
- Anchors
Troubleshooting
- Pattern matching
- File permissions
- Backup issues
- Syntax errors
- Line endings