Table of content

Sed Command in Linux

The sed command replaces a string in a file with a new string.

sed command can find and delete a line. It is capable of removing empty lines. It can remove the first or any number of lines in a file. It replaces tabs with spaces and also specific lines from a file.

The command sed 's/Admin/Root/g' sedcommand shall replace Admin and place Root in the sedcommand file.

linux-systemadmin1

Please note - The change from Admin to Root is reflected as an output to the sed command and not within the content of the sedcommand file.

To reflect the change within the file content, the command is.

sed -i 's/Admin/Root/g' sedcommand

The command sed '/Admin/d' sedcommand shall remove every line that has Admin.

linux-systemadmin2

To remove empty lines within the file content, the command is.

sed '/^$/d' filename

To remove the first line within the file content, the command is.

sed '1d' filename

The command sed '1,2d' sedcommand shall remove the first two lines of the sedcommand file.

linux-systemadmin3

To remove the tabs with spaces, the command is.

sed 's/\t/ /g' file

To remove the spaces with tabs, the command is.

sed 's/ /\t/g' file

To show lines from the second to the fourth line of a file, the command is:

sed -n 2,4p file

To show lines except for the ones from the second to the fourth line of a file, the command is:

sed 2,4d file

The command sed G sedcommand shall add an empty line after each line in the sedcommand file.

linux-systemadmin4

The command sed '1!s/Linux/L/' sedcommand shall replace all Linux with L except for the first occurrence in the sedcommand file.

linux-systemadmin5

To replace Admin and place Root within the sedcommand file inside the vi editor, the command is.

:%s/Admin/Root
About Author :

Myself Debomita Bhattacharjee, an IT employee with 6+ years of experience in Software industry. My area of interest is Automation testing and Front End Development.

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions