133 lines
2.2 KiB
Markdown
133 lines
2.2 KiB
Markdown
# Comprehensive SED Cheat Sheet
|
|
|
|
## Table of Contents
|
|
|
|
1. [SED Basics](#sed-basics)
|
|
2. [Print Operations](#print-operations)
|
|
3. [Substitution](#substitution)
|
|
4. [Deletion](#deletion)
|
|
5. [Insertion](#insertion)
|
|
6. [Append and Replace](#append-and-replace)
|
|
7. [Selective Printing](#selective-printing)
|
|
8. [Text Formatting](#text-formatting)
|
|
9. [Multiple Commands](#multiple-commands)
|
|
10. [Regular Expressions](#regular-expressions)
|
|
11. [Grouping and Backreferences](#grouping-and-backreferences)
|
|
12. [File In-Place Editing](#file-in-place-editing)
|
|
13. [SED Scripts](#sed-scripts)
|
|
|
|
## SED Basics
|
|
|
|
### Basic Syntax
|
|
|
|
```bash
|
|
sed 'command' filename
|
|
```
|
|
|
|
### In-Place Editing
|
|
|
|
```bash
|
|
sed -i 'command' filename
|
|
```
|
|
|
|
## Print Operations
|
|
|
|
```bash
|
|
# Print All Lines
|
|
sed -n 'p' filename
|
|
|
|
# Print Line Numbers
|
|
sed -n '10p' filename
|
|
|
|
# Print Range of Lines
|
|
sed -n '5,10p' filename
|
|
```
|
|
|
|
## Substitution
|
|
|
|
```bash
|
|
# Substitute Text
|
|
sed 's/pattern/replacement/' filename
|
|
|
|
# Global Substitution
|
|
sed 's/pattern/replacement/g' filename
|
|
```
|
|
|
|
## Deletion
|
|
|
|
```bash
|
|
# Delete Matching Lines
|
|
sed '/pattern/d' filename
|
|
|
|
# Delete Lines by Number
|
|
sed '5d' filename
|
|
```
|
|
|
|
## Insertion
|
|
|
|
```bash
|
|
# Insert Line Before Matching Pattern
|
|
sed '/pattern/i new_line' filename
|
|
```
|
|
|
|
## Append and Replace
|
|
|
|
```bash
|
|
# Append Line After Matching Pattern
|
|
sed '/pattern/a new_line' filename
|
|
|
|
# Replace Line with New Text
|
|
sed '/pattern/c new_line' filename
|
|
```
|
|
|
|
## Selective Printing
|
|
|
|
```bash
|
|
# Print Lines Matching Pattern
|
|
sed -n '/pattern/p' filename
|
|
```
|
|
|
|
## Text Formatting
|
|
|
|
```bash
|
|
# Convert to Uppercase
|
|
sed 'y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/' filename
|
|
```
|
|
|
|
## Multiple Commands
|
|
|
|
```bash
|
|
# Execute Multiple Commands
|
|
sed -e 'command1' -e 'command2' filename
|
|
```
|
|
|
|
## Regular Expressions
|
|
|
|
```bash
|
|
# Use Regular Expressions
|
|
sed '/^pattern/s/replacement/' filename
|
|
```
|
|
|
|
## Grouping and Backreferences
|
|
|
|
```bash
|
|
# Use Grouping and Backreferences
|
|
sed 's/\(pattern1\)\(pattern2\)/\2\1/' filename
|
|
```
|
|
|
|
## File In-Place Editing
|
|
|
|
```bash
|
|
# In-Place Editing with Backup
|
|
sed -i.bak 's/pattern/replacement/' filename
|
|
```
|
|
|
|
## SED Scripts
|
|
|
|
```bash
|
|
# Create and Use SED Script
|
|
echo 's/pattern/replacement/' > myscript.sed
|
|
sed -f myscript.sed filename
|
|
```
|
|
|