Bash: remove all lines of input except last n lines

10,986

Solution 1

To remove the last 2 lines you can use something like this:

head -n $(($(wc -l < "$filename") - 2)) "$filename"

Not very elegant but it should work. I use wc -l to count the number of lines and then I use head to only display the first number of lines minus 2 lines.

EDIT: to keep only last N lines you could do

tail -n $N $filename

To keep only first N lines you could do.

head -n $N $filename

It seems I may have misunderstood your question and that is why I add these two commands.

Solution 2

From the head man page:

-n, --lines=[-]N
      print  the first N lines instead of the first 10; with the lead-
      ing ‘-’, print all but the last N lines of each file

which means ... | head -n -2 will do what you want.

Just as an alternative, the following also works, though I imagine its efficiency is not at all good for large files.

tac file | awk 'NR>2' | tac

Solution 3

i want to remove all lines except n last

Easiest way is to do (let n=5):

tail -n5 $filename > $filename.tmp && mv $filename.tmp $filename

This will output last five lines to new file and than rename it.

If the task is opposite - you need all lines, but 5 last, you can to do:

head -n$((`cat $filename | wc -l` - 5)) $filename > $filename.tmp && mv $filename.tmp $filename

Solution 4

To keep last 1000 lines of a file (Ex: alert_PROD.log)

tail -1000 alert_PROD.log > alert_tmp ; cat alert_tmp > alert_PROD.log ; rm alert_tmp

To keep top 1000 lines use head instead of tail command:

head -1000 alert_PROD.log > alert_tmp ; cat alert_tmp > alert_PROD.log ; rm alert_tmp
Share:
10,986
rupat
Author by

rupat

Updated on June 17, 2022

Comments

  • rupat
    rupat almost 2 years

    i want to remove all lines except n last or first n lines with a short one-liner

    eg.:

    ---
    
    aaaa
    
    bbbb
    
    cccc
    
    dddd
    
    cat/echo/find ...  | sed < all except last 2 lines > 
    

    should result

    aaaa
    
    bbbb
    
    ---
    
    aaaa
    
    bbbb
    
    cccc
    
    dddd
    
    eeee
    
    ffff
    
    cat/echo/find ...  | sed < all except last 2 lines > 
    

    should result

    aaaa
    
    bbbb
    
    cccc
    
    dddd
    
    ---
    

    I need this also for very high n´s. So it could possible to set n=100 or so ;)

    Thanx for any help !