Deleting a Specific Line From a Text File in Command Line in 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

Eric Ma

Eric is a 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.

3 comments:

  1. This was very helpful.
    Question.
    Once we have the offending line removed, how do we (using the command line) overwrite the file with the new, corrected version?

    For example…
    sed ‘//d’ file.txt
    removes the html expression but now I want to save this version to the same file.

    Thank you for any suggestions.

  2. Greetings. I found the answer. Insert -i after sed command.

    sed -i ‘//d’ file.txt
    overwrites the file with the corrected information.

    But

    What if the expression to remove contains a forward slash character. Haven’t figured out how to make this work.

    sed -i ‘//d’ file.txt

    There must be a way to escape the / character in the expression to remove. I’ve tried surrounding it with ‘ and \. Nether seem to be the solution.

    1. Hai we can delete a particular line in text file using sed command. But again how to recover that deleted text in that filename after deleting if by a mistake?

Leave a Reply

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