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.
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.
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
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
$ 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.
printf 'apple\nbanana\nbanana: celery\n\ndates,fish,grapes\n' | sed '/banana:/,$d'
– Victoria Stuart Apr 30 '19 at 16:32