How to use sed to remove the last n lines of a file

mezda picture mezda · Nov 14, 2012 · Viewed 232k times · Source

I want to remove some n lines from the end of a file. Can this be done using sed?

For example, to remove lines from 2 to 4, I can use

$ sed '2,4d' file

But I don't know the line numbers. I can delete the last line using

$sed $d file

but I want to know the way to remove n lines from the end. Please let me know how to do that using sed or some other method.

Answer

ams picture ams · Nov 14, 2012

I don't know about sed, but it can be done with head:

head -n -2 myfile.txt