DomainsFeatured DomainsFeatured - 2 months ago 14
Linux Question

How To Delete First X Lines Based On Minimum Lines In File

I have a file with 10,000 lines. Using the following command, I am deleting all lines after line 10,000.

sed -i '10000,$ d' file.txt

However, now I would like to delete the first X lines so that the file has no more than 10,000 lines.

I think it would be something like this:

sed -i '1,$x d' file.txt

would be the number of lines over 10,000. I'm a little stuck on how to write the if, then part of it. Or, I was thinking I could use the original command and just
the file in reverse?

Of course, if you know a more efficient way to write the command, I would be open to that too. Your positive input is highly appreciated.


For simplicity, I would reverse the file, keep the first 10000 lines, then re-reverse the file.

It makes saving the file in-place a touch more complicated

tac "$source" | sed '10000 q' | tac > "$temp" && mv "$temp" "$source"

Without reversing the file, you'd count the number of lines and do some arithmetic:

sed -i "1,$(( $(wc -l < file.txt) - 10000 )) d" file.txt