sed
(stream editor) is a powerful text stream editor that is used to perform basic text transformations on an input stream. Below is a cheat sheet with commonly used sed
commands and syntax:
Basic Syntax
sed OPTIONS 'COMMAND' INPUT_FILE
Common Commands
Print Lines:
sed -n 'p' filename
Substitute (Search and Replace):
sed 's/old_text/new_text/g' filename
Delete Lines:
sed '/pattern/d' filename
Print Specific Line:
sed -n '5p' filename
Print Range of Lines:
sed -n '2,5p' filename
Modifiers
Global Replace (All Occurrences):
sed 's/old_text/new_text/g' filename
Case Insensitive Replace:
sed 's/old_text/new_text/gI' filename
Insert and Append
Insert Text Before a Line:
sed '/pattern/i new_text' filename
Append Text After a Line:
sed '/pattern/a new_text' filename
Delete Empty Lines
sed '/^$/d' filename
Print Line Numbers:
sed -n '1,10p' filename
Print Last N Lines:
sed -n '$-N,$p' filename
Basic Regular Expressions
Match Lines Starting with a Pattern:
sed -n '/^pattern/p' filename
Match Lines Ending with a Pattern:
sed -n '/pattern$/p' filename
Reading Commands from a File
sed -f scriptfile filename
In-Place Editing
Edit File In-Place:
sed -i 's/old_text/new_text/g' filename
Printing Lines Around a Match
Print N Lines Before a Match:
sed -n '/pattern/{N;p}' filename
Print N Lines After a Match:
sed -n '/pattern/{N;N;p}' filename
Append Line Numbers to Each Line
sed = filename | sed 'N;s/\n/ /'
Special Characters in Replacement String
Insert Tab Character:
sed 's/old_text/\tnew_text/g' filename
Insert Newline Character:
sed 's/old_text/new_text\
/g' filename
Note
sed
commands can vary slightly based on the version ofsed
and the operating system.- The examples provided assume usage on Unix/Linux systems.
- Always refer to the
sed
documentation orman
pages for comprehensive information.
This cheat sheet covers some commonly used sed
commands. Adjustments may be necessary based on specific use cases and requirements.