Sed Command in Linux with Practical Examples
The “sed” command in Linux is a powerful tool for performing basic text transformations on an input stream or a file. It operates by reading input line by line, and applying a set of commands to each line. These commands can be used to replace, insert, or delete text, making it a versatile tool for editing files.
One of the most common uses of sed is to replace a specific word or phrase in a file. For example, let’s say we have a file called “example.txt” with the following contents:
This is the first line of the file.
This is the second line of the file.
This is the third line of the file.
If we want to replace the word “first” with “second” on the first line of the file, we can use the following sed command:
sed 's/first/second/' example.txt
This command tells sed to perform a substitution, replacing the first occurrence of “first” with “second” on the first line of the file. The output of this command will be:
This is the second line of the file.
This is the second line of the file.
This is the third line of the file.
We can also use sed to make changes to multiple lines. For example, if we want to replace the word “line” with “lines” throughout the entire file, we can use the following command:
sed 's/line/lines/g' example.txt
The “g” at the end of the command tells sed to perform the replacement globally, on all occurrences of the word “line” in the file. The output of this command will be:
This is the first lines of the file.
This is the second lines of the file.
This is the third lines of the file.
Sed can also be used to insert text, or even delete lines. For example, if we want to insert a new line after the second line of the file, we can use the following command:
sed '2a\
This is a new line.' example.txt
This command tells sed to insert the text “This is a new line.” after the second line of the file. The output of this command will be:
This is the first line of the file.
This is the second line of the file.
This is a new line.
This is the third line of the file.
As you can see, the sed command is a powerful tool that can be used to perform a wide variety of text transformations on a file. For more information on using sed, you can refer to the man pages or online resources.
Subroto Mondal
Latest posts by Subroto Mondal (see all)
- Installing and Configuring OpenShift: A Step-by-Step Guide for Linux Experts with Terminal Code - February 19, 2023
- Sed Command in Linux with Practical Examples - February 19, 2023
- Rsync Command uses with examples - February 19, 2023