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
asked Jan 13, 2015 by anonymous

1 Answer

 
Best answer

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 Jan 13, 2015 by Eric Z Ma (44,280 points)

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...