Press Ctrl/Cmd + P to print
or save as PDF

Basic Sed Command in Linux VPS Server

The Linux SED command is a useful tool for performing general tasks such as parsing and transforming text. The SED command is now available in most of the major operating systems. While SED’s script-based syntax appears to be difficult at first, it could help in solving multiple complex tasks in just a few lines.

In this article, we will be discussing the basics of the SED command to improve your workflow in your Linux VPS server.

Delete Command

To perform a delete command with sed command, use the d option such as shown in the following command to delete a line from a text file. For example, using the following text file name “text.txt”, with the following contents as an example.

> cat text.txt
macOS
Ubuntu
Linux Mint
Debian

To delete the first line of the contents, run the following sed command with the “d” option to delete the first line of the contents.

> sed '1d' text.txt
Ubuntu Linux Mint Debian

Write Command

Using the similar text file, “text.txt”, to read a certain line and write it into a new file, you may use the “w” option to specify which line to write into the new file. Run the following command to write the second line of “text.txt” into the “text2.txt”.

> sed '2~2 w text2.txt' text.txt
> cat text2.txt
Linux Mint

Append Command

The append command allows you to add contents after a line using the “a” option. For example, to append a new content within the “text.txt” file, run the following command with the “a” option.

> sed '2 a Windows' text.txt
> cat text.txt
Ubuntu
Linux Mint
Windows
Debian

The command above appends a new word called “Windows” into the text file after line 2, which is after the line with “Linux Mint”.

Read Command

The read command will allow you to read the file content out from the specified file using the “r” option. Using the existing “text.txt” and “text2.txt” files as examples, run the following sed command.

> sed '3 r text2.txt' text.txt
Ubuntu
Linux Mint
Windows
Linux Mint
Debian

This command read the “text2.txt” file after reading the third line of the “text.txt” file before returning back to the normal sequence. Hence, the Linux Mint after the line ” Windows” was read from the “text2.txt”. That is all for the SED basic commands, hope this guide is helpful to you.