Introduction to sed
sed
(stream editor) is a powerful text processing tool in Unix and Unix-like operating systems. It is used to perform basic text transformations on an input stream (a file or input from a pipeline). sed
is commonly used for:
- Searching and replacing text
- Inserting and deleting lines
- Performing complex text manipulations
Basic Syntax
The basic syntax of sed
is:
options
: Command-line options to modify the behavior ofsed
.script
: A set of instructions to be executed on the input text.inputfile
: The file to be processed. If omitted,sed
reads from standard input.
Commonly Used Options
-e script
: Add the script to the commands to be executed.-f script-file
: Add the contents of the script-file to the commands to be executed.-i[SUFFIX]
: Edit files in place (makes backup if SUFFIX supplied).-n
: Suppress automatic printing of pattern space.
Basic Commands
Substitution Command
The substitution command (s
) is used to replace occurrences of a pattern with a replacement string.
Example:
Output:
Deleting Lines
The delete command (d
) is used to delete lines matching a pattern.
Example:
Output:
Inserting and Appending Text
i\text
: Insert text before a line.a\text
: Append text after a line.
Example:
Output:
Practical Examples
Example 1: Replacing Text in a File
Replace all occurrences of "foo" with "bar" in a file:
Example 2: Deleting Blank Lines
Remove all blank lines from a file:
Example 3: Inserting a Line After a Match
Insert "New Line" after every line containing "pattern":
Example 4: Using sed with Pipelines
Combine sed
with other commands using pipelines:
Exercises
Exercise 1: Basic Substitution
Replace "apple" with "orange" in the following text:
Solution:
Output:
Exercise 2: Deleting Specific Lines
Delete lines containing the word "delete" from the following text:
Solution:
Output:
Exercise 3: Inserting Text
Insert "Start of File" at the beginning of the file:
Solution:
Output:
Common Mistakes and Tips
- Forgetting the
g
flag: When replacing all occurrences of a pattern in a line, don't forget to use theg
flag. - Using single quotes: Always use single quotes around the
sed
script to avoid shell interpretation of special characters. - Backup files: When using
-i
for in-place editing, consider making a backup by providing a suffix (e.g.,-i.bak
).
Conclusion
In this section, we covered the basics of using sed
for text processing, including substitution, deletion, and insertion of text. We also explored practical examples and exercises to reinforce the concepts. Understanding sed
is crucial for efficient text manipulation in Bash scripting, and it serves as a foundation for more advanced text processing tasks.
Bash Programming Course
Module 1: Introduction to Bash
Module 2: Basic Bash Commands
- File and Directory Operations
- Text Processing Commands
- File Permissions and Ownership
- Redirection and Piping