Catalog / Sed Text Manipulation Cheatsheet
Sed Text Manipulation Cheatsheet
A comprehensive cheat sheet for the `sed` stream editor, covering essential commands, syntax, and use cases for text manipulation.
Basic Usage
Syntax
Where:
|
Common Options
|
In-place editing (GNU sed). Requires no extension or an empty string as an argument (BSD). Example: |
|
Add the script to the commands to be executed. Example: |
|
Suppresses automatic printing of pattern space. Example: |
|
Parse script from file Example: |
|
Read content from file, and append to current file Example: |
Basic Commands
|
Substitute ‘pattern’ with ‘replacement’. Example: |
|
Global substitution. Replaces all occurrences in a line. Example: |
|
Case-insensitive substitution. Example: |
|
Print the current pattern space. Example: |
|
Delete the current pattern space (line). Example: |
Advanced Text Manipulation
Using Addresses
|
Substitute only on line 2. |
|
Substitute on lines 2 through 5. |
|
Substitute on line 2 to the end of the file. |
|
Substitute between lines matching /start/ and /end/. |
Delete Specific Lines
|
Delete the first line. |
|
Delete the last line. |
|
Delete lines 1 to 3. |
|
Delete lines matching the pattern. |
Insert and Append Text
|
Insert ‘Text to insert’ before line 2. |
|
Append ‘Text to append’ after line 2. |
|
Insert text before lines matching ‘pattern’. |
|
Append text after lines matching ‘pattern’. |
Regular Expressions with Sed
Basic Regex
|
Matches any single character except newline. Example: |
|
Matches zero or more occurrences of the preceding character. Example: |
|
Matches any single character within the brackets. Example: |
|
Matches the beginning of a line (when inside brackets, negates the character class). Example: |
|
Matches the end of a line. Example: |
Extended Regex
|
Matches one or more occurrences of the preceding character (requires Example: |
|
Matches zero or one occurrence of the preceding character (requires Example: |
|
Specifies alternation (requires Example: |
|
Groups parts of the regex together (requires Example: |
Character Classes
|
Alphanumeric characters. |
|
Alphabetic characters. |
|
Digits (0-9). |
|
Whitespace characters (space, tab, newline). |
|
Uppercase alphabetic characters. |
|
Lowercase alphabetic characters. |
Practical Sed Examples
Numbering Lines
Adds line numbers to each line. |
Remove Blank Lines
Deletes all blank lines from file.txt. |
Convert DOS to Unix Line Endings
Removes carriage return characters at the end of lines. |
Extract Data
Extract IP Address from interface config: |
|
Working with variables
Using shell variables in sed: |
|