Delete Lines from a File Using SED

Unix utility SED provides an effective and versatile way of deleting one or more lines from a designated file to match the needs of the user. This Unix command is used for command line processing.

SED Utility Purpose

This utility can be used to delete expressions from a file which can be identified by a specifying delimiter (such as a comma, tab, or space), by line number, or by searching for a string, expression or the address of a line in the syntax of Sed.

Sed: Delete One or More Lines from a File

Here is how to remove one or more lines from a file.

Syntax

sed '{[/]||[/]}d'

sed '{[/][,][/]d'

/.../=delimiters

n = line number

string = string found in in line

regex = regular expression corresponding to the searched pattern

addr = address of a line (number or pattern )

d = delete

Examples of Sed

Here are some examples of how to use the above syntax.

Use the following code to remove the third line:

sed '3d' fileNamet

Remove the line containing the string "awk," by using:

sed '/awk/d' filenamet

You can remove the last line by typing in:

sed '$d' filenamet

Or remove all empty lines through:

sed '/^$/d' filenamet

sed '/./!d' filenamet

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' filenamet

Remove the interval between lines 7 and 9:

sed '7,9d' filenamet

The same operation as above but replacing the address with parameters:

sed '/-Start/,/-End/d' filenamet

The above examples are only changed at the display of the file (stdout1= screen).

For permanent changes to the old versions (<4) use a temporary file for GNU sed using the "-i[suffix]":

sed -i".bak" '3d' filenamet

Image: © Jaroslav Machacek - Shutterstockom

Leave A Comment