cheetsheetz/sed.md

2.2 KiB

Comprehensive SED Cheat Sheet

Table of Contents

  1. SED Basics
  2. Print Operations
  3. Substitution
  4. Deletion
  5. Insertion
  6. Append and Replace
  7. Selective Printing
  8. Text Formatting
  9. Multiple Commands
  10. Regular Expressions
  11. Grouping and Backreferences
  12. File In-Place Editing
  13. 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