sed
Introduction
This cheat sheet provides a quick reference for some common sed (stream editor) commands and concepts. sed is a powerful text manipulation tool in Unix-like operating systems.
sed Concepts
Basic sed Usage
sed is used to perform text transformations on input text (a file or input stream) using a set of commands.
Replace text in a file and print the result:
sed 's/old-text/new-text/' file.txtReplace text in a file and save the changes in-place:
sed -i 's/old-text/new-text/' file.txtReplace text globally (all occurrences):
sed 's/old-text/new-text/g' file.txt
Regular Expressions
sed uses regular expressions for pattern matching and manipulation.
Use a regular expression as a pattern:
sed '/pattern/s/old-text/new-text/' file.txtMatch lines that start with a pattern:
sed '/^start/s/old-text/new-text/' file.txtMatch lines that end with a pattern:
sed '/end$/s/old-text/new-text/' file.txt
Addressing Lines
You can specify line addresses to target specific lines in a file.
Apply the
scommand to lines 1 to 5:sed '1,5 s/old-text/new-text/' file.txtApply the
scommand to lines matching a pattern:sed '/pattern/ s/old-text/new-text/' file.txt
Reading from Files
sed can read commands from a file.
- Read
sedcommands from a file and apply them:sed -f script.sed input.txt
Deleting Lines
sed can delete lines from a file.
Delete lines matching a pattern:
sed '/pattern/d' file.txtDelete lines between two patterns (inclusive):
sed '/start/,/end/d' file.txt
sed Command-Line
Replace text in a file and print the result:
sed 's/old-text/new-text/' file.txtReplace text in a file and save the changes in-place:
sed -i 's/old-text/new-text/' file.txtReplace text globally (all occurrences):
sed 's/old-text/new-text/g' file.txtUse a regular expression as a pattern:
sed '/pattern/s/old-text/new-text/' file.txtMatch lines that start with a pattern:
sed '/^start/s/old-text/new-text/' file.txtApply the
scommand to lines 1 to 5:sed '1,5 s/old-text/new-text/' file.txtRead
sedcommands from a file and apply them:sed -f script.sed input.txtDelete lines matching a pattern:
sed '/pattern/d' file.txtDelete lines between two patterns (inclusive):
sed '/start/,/end/d' file.txt
Conclusion
This cheat sheet covers some common sed (stream editor) commands and concepts. sed is a versatile text manipulation tool, making it essential for text processing and editing tasks; refer to the GNU sed documentation for more in-depth information and advanced usage.