3

This question already has an answer here:

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

marked as duplicate by Anthon, Archemar, dr01, dhag, X Tian Oct 6 '15 at 15:14

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

7

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).

  • 2
    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? – user1717828 Oct 6 '15 at 13:37
  • 2
    @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
  • 6
    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
0

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 – Jimmy Obonyo Abor Oct 15 '17 at 21:48
-2
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.