8

I have a file with many lines.

I want to delete from the line 1458 to the end of the file. I think that I can do it with sed, but I do not know how to.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
alloppp
  • 433

3 Answers3

19
sed '1458,$d'

You can use that with -i to edit the file in place if necessary.

e.g

sed -i '1458,$d' filename.txt
5

There are many possibilities to do that, but if the file is very big it is better to stop processing any lines after given position and just quit. This is exactly what the command q is designed for in sed:

sed 1458q file
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
jimmij
  • 47,140
2
$ head -n 1458 myfile > myfile.tmp ; mv myfile.tmp myfile

Side note: To my knowledge, there's no clear way to shorten a file (in bash/shell etc) based on number of lines, that doesn't involve creating a new file first (which is what sed, or sed -i(n place) does.) This matters if remaining disk space is insufficient to accommodate the newly written file. In that case, if you can roughly guess as to the size of the new file, truncate -s {number of bytes} myfile does lop the end of the file off, without creating a new one.

Stephan
  • 2,911