Using sed - Comprehensive Tutorial
Introduction to sed
The sed (stream editor) command in Unix/Linux is a powerful tool for text processing. It allows you to perform basic text transformations on an input stream (a file or input from a pipeline). In this tutorial, we will cover the basics of using sed with various examples.
Basic Syntax
The basic syntax of sed is:
sed [options] 'command' file
Here is a breakdown of the segments:
- sed: The command itself.
- [options]: Optional flags that modify the behavior of sed.
- 'command': The action to perform on the input text.
- file: The name of the file to be processed.
Example 1: Replacing Text
One of the most common uses of sed is replacing text patterns. The syntax for replacing text is:
sed 's/old_text/new_text/' file
Example:
sed 's/hello/hi/' input.txt
This command replaces the first occurrence of hello with hi in each line of input.txt.
hello world hi world
Example 2: Global Replacement
To replace all occurrences of a pattern in a line, use the g (global) flag:
sed 's/old_text/new_text/g' file
Example:
sed 's/hello/hi/g' input.txt
This command replaces all occurrences of hello with hi in each line of input.txt.
hello hello world hi hi world
Example 3: Deleting Lines
You can use sed to delete lines that match a specific pattern. The syntax is:
sed '/pattern/d' file
Example:
sed '/hello/d' input.txt
This command deletes all lines containing the word hello in input.txt.
world hi world
Example 4: Inserting and Appending Text
You can insert or append text before or after a line that matches a pattern.
To insert text before a pattern:
sed '/pattern/i\new_text' file
Example:
sed '/hello/i\This is a new line' input.txt
This is a new line hello world
To append text after a pattern:
sed '/pattern/a\new_text' file
Example:
sed '/hello/a\This is a new line' input.txt
hello world This is a new line
Example 5: Substituting Text with Regular Expressions
sed supports regular expressions for advanced pattern matching and substitution.
Example:
sed 's/[0-9]\+/NUMBER/g' input.txt
This command replaces all sequences of digits with the word NUMBER in input.txt.
hello 123 world hello NUMBER world
Conclusion
In this tutorial, we have covered the basics of using sed for text processing. We looked at how to replace text, perform global replacements, delete lines, insert and append text, and use regular expressions with sed. With these foundational skills, you can start using sed to perform powerful text manipulations in your own scripts and command-line tasks.