How do I delete the last n lines of an ascii file using shell commands?


With head (removes the last 2 lines):

head -n -2 file

With sed/tac (removes the last 2 lines):

tac file | sed "1,2d" | tac

tac reverses the file, sed deletes (d) the lines 1 to 2 (2 can be any number).

  • 5
    Why is it when I try redirecting the output back into the file (OP asked to delete the lines of the file, after all), I just get a blanked file: $ head -n -2 test-file > test-file When I pick another file name, the head output redirects as I would expect? What's the best way to do the redirect into the same file? Oct 6 '15 at 13:37
  • 5
    @user1717828 The problem is that bash processes the redirections first, then executes the command. When >file is processed bash creates (if not existing) an empty file, else it is truncated. head then prints nothing because the file it reads is empty. You have to go via a temporary file. head -n -2 file >tmp && mv tmp file. BTW: all tools which allow "inplace editing" (like sed -i, gawk -i inplace, perl -i) do exactly the same.
    – chaos
    Oct 6 '15 at 13:53
  • 7
    head -n -2 is great but is not supported by all versions of head, in particular the bsd version that ships with mac os :-(
    – phs
    Aug 4 '16 at 9:29

Have a look at the manpage for head - you can specify a number of lines, and it will give you that many lines out of a file.

head -10 filename 

Gives first 10 lines of a file. If you don't know how long your file is, you can use wc -l to count the number of lines. And then use head to print the appropriate number.

  • question is about deleting n lines not outputing/print Oct 15 '17 at 21:48
  • ... | tee filename | sponge filename can be valuable when you want to print it AND redirect it to a file. Aug 8 '19 at 22:11
tac file| sed -i 'nd' | tac

tac reverses the file, sed deletes (d) the lines n numbers of lines

  • or sed -i "\$-${n},\$d" file
    – Archemar
    Oct 6 '15 at 13:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.