delete n last lines of a file

Hello!!!

how can I delete the last n lines of a file???

Thanks

Refer this

if you have a better head

head -n -10 file

Assuming you want to remove the last 22 lines:

tac filename | tail -n +23 | tac

What this does:

  1. Reverse the file.
  2. Take all but the first 22 lines.
  3. Reverse the file again (back to the original order).

Note that the number tells it at which line to start, so 2 will cut off the first line, 50 will cut off 49 lines, etc.

ShawnMilo

Or:

perl -0777pe's/(?:.*\n){10}\z//' file

Or in-place with ed:

printf '$-9,$d\nw'|ed - file

I tried using the command 'tac' . i get an error command not 'found'.. how do delete the last three lines from the file..please help

If you know the number of lines, subtract three and print up through that number.

Radoulov's solutions are superior, as usual, although they will read the entire file into memory at once, whereas the following basically operates the file a line at a time.

lines=$(wc -l <inputfile)
wanted=`expr $lines - 3`
head -n $wanted inputfile >outputfile

This is not memory-intensive, and will work.

cat filename | perl -ne 'push(@a, $_); print shift(@a, ) if  $#a >=3 ;'