How to use a SED in Linux

SED provides an effective and a flexible way of removing one or more lines from a specific file to suit the needs of the user. This Linux command is used for command line handling.

Syntax:

sed -i ‘/Text to Delete/d’ /path/to/file

Here are the examples how we can remove one or more lines from a file:

Examples:

Remove the 3rd line from file:

sed '3d' fileName.txt

Remove the line containing the string “gmail”:

sed '/gmail/d' filename.txt

To remove the last line:

sed '$d' filename.txt

To remove all empty lines:

sed '/^$/d' filename.txt       
sed '/./!d' filename.txt

Remove all lines from /var/log/messages having string “REMOVE THIS TEXT” and restore output in new file. Do not make any changes in original line.

$ sed "/REMOVE THIS TEXT/d" /var/log/messages > messages.txt

Remove all lines from /var/log/messages having string “REMOVE THIS TEXT” in same file.

$ sed -i "/REMOVE THIS TEXT/d" /var/log/messages

Remove the line matching by a regular expression (by eliminating one containing digital characters, at least 1 digit, located at the end of the line):

sed '/[0-9/][0-9]*$/d' filename.txt

Remove the interval between lines 7 and 9:

sed '7,9d' filename.txt