How to delete a specific line from a text file in command line on Linux?

On Linux, how to delete a specific line from a text file in command line? For example, to delete the 4th line from a file

aaa
bbb
ccc
ddd
eee
ffffff

You can use the “stream editor for filtering and transforming text” sed.

With GNU sed:

sed -i '4d' ./file

Here, -i means edit the file inplace. d is the command to “delete the pattern space; immediately start next cycle”. 4 means the 4th line.

The file content will be:

aaa
bbb
ccc
eee
ffffff

There are more combinations for deleting lines. Some examples are:

Remove the last line:

sed '$d' filename.txt

Remove all empty lines:

sed '/^$/d' ./file

or

sed '/./!d' ./file

Remove lines from 7 to 9:

sed '7,9d' ./file

Remove the line matching by a regular expression REGULAR:

sed '/REGULAR/d' ./file

For a simple example, remove the lines containing “oops”:

sed '/oops/d' ./file
Answered by Eric Z Ma.

Eric Z Ma

Eric is a father and systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *