2.2 KiB
2.2 KiB
Comprehensive SED Cheat Sheet
Table of Contents
- SED Basics
- Print Operations
- Substitution
- Deletion
- Insertion
- Append and Replace
- Selective Printing
- Text Formatting
- Multiple Commands
- Regular Expressions
- Grouping and Backreferences
- File In-Place Editing
- SED Scripts
SED Basics
Basic Syntax
sed 'command' filename
In-Place Editing
sed -i 'command' filename
Print Operations
# Print All Lines
sed -n 'p' filename
# Print Line Numbers
sed -n '10p' filename
# Print Range of Lines
sed -n '5,10p' filename
Substitution
# Substitute Text
sed 's/pattern/replacement/' filename
# Global Substitution
sed 's/pattern/replacement/g' filename
Deletion
# Delete Matching Lines
sed '/pattern/d' filename
# Delete Lines by Number
sed '5d' filename
Insertion
# Insert Line Before Matching Pattern
sed '/pattern/i new_line' filename
Append and Replace
# Append Line After Matching Pattern
sed '/pattern/a new_line' filename
# Replace Line with New Text
sed '/pattern/c new_line' filename
Selective Printing
# Print Lines Matching Pattern
sed -n '/pattern/p' filename
Text Formatting
# Convert to Uppercase
sed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/' filename
Multiple Commands
# Execute Multiple Commands
sed -e 'command1' -e 'command2' filename
Regular Expressions
# Use Regular Expressions
sed '/^pattern/s/replacement/' filename
Grouping and Backreferences
# Use Grouping and Backreferences
sed 's/\(pattern1\)\(pattern2\)/\2\1/' filename
File In-Place Editing
# In-Place Editing with Backup
sed -i.bak 's/pattern/replacement/' filename
SED Scripts
# Create and Use SED Script
echo 's/pattern/replacement/' > myscript.sed
sed -f myscript.sed filename