4

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

chaos
  • 48,171
user137256
  • 73
  • 1
  • 1
  • 2

3 Answers3

13

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

chaos
  • 48,171
  • 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? – user1717828 Oct 06 '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 06 '15 at 13:53
  • 8
    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 04 '16 at 09: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.

Sobrique
  • 4,424
-2
tac file| sed -i 'nd' | tac

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

Anthon
  • 79,293