Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

How can I discard the last n lines of a file with a unix command line filter?

That would be sort of the opposite of tail: tail discards the first n lines but pipes the rest through, but I want the command to pipe everything through except the last n lines.

Unfortunately I haven't found anything like that - head doesnt help, too. EDIT: At least in Solaris it does not take negative arguments.

share|improve this question
    
FYI when using head: By placing ‘-’ in front of the number with -n option, it prints all the lines of each file but not the last N lines as shown below, –  G Koe Jan 30 '13 at 13:46

2 Answers 2

If you have GNU head, you can use

head -n -5 file.txt

to print all but the last 5 lines of file.txt.

If head -n takes no negative arguments, try

head -n $(( $(wc -l file.txt | awk '{print $1}') - 5 )) file.txt
share|improve this answer
4  
(and pray that file.txt is at least six lines long...) –  Michael Kjörling Jan 30 '13 at 14:59

I'm curious why you think head is not an option:

~$ man head
...
-n, --lines=[-]K
        print the first K lines instead of the first 10; 
        with the leading `-', print all but the last K lines of each file

This seems to fit your purpose, using, for example:

head -n -20 yourfile.txt
share|improve this answer
1  
Note that this only applies to GNU head. BSD head doesn't have this option, so this answer will not work on Solaris or other Unixes without GNU coreutils. The OP specifically tagged this with Unix and Unix-Utils too. –  slhck Jan 30 '13 at 14:06
    
@slhck Not to mention the fact that the OP mentioned that this is for Solaris. –  Michael Kjörling Jan 30 '13 at 15:00
    
Unfortunately someone removed my mention of Solaris. But I should have mentioned anyway that the version of head does not support that. –  hstoerr Jan 30 '13 at 16:47
    
Sorry all. Did not notice Solaris, nor was I aware of the various versions of head. –  Anders R. Bystrup Jan 30 '13 at 18:00
    
@hstoerr Solaris is now in your tags :) –  slhck Jan 30 '13 at 19:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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