Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Where $x 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 cat the file in reverse?

For example, if we wanted just 3 lines from the bottom (seems simpler after a few helpful answers):

Input:

Example Line 1
Example Line 2
Example Line 3
Example Line 4
Example Line 5

Expected Output:

Example Line 3
Example Line 4
Example Line 5

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.

like image 253
DomainsFeatured Avatar asked Nov 11 '16 21:11

DomainsFeatured


People also ask

How do I remove the first N line from a file?

Using the tac and the sed Commands However, if we can reverse the order of lines in the input file, the problem will turn into “remove first n lines from a file.” A straightforward sed one-liner sed '1,n d' can remove the top n lines. After that, if we reverse the lines again, our problem gets solved.

How do you remove the first 100 lines in Notepad ++?

Ctrl-F2 on the line you wish to keep. This bookmarks the current line (you will see a blue circle at start of line). Then Use the “remove unmarked lines” which is under “Search” main menu, then “Bookmark” item. With “normal” size files, those work find, followed by DELETE or BACKSPACE to delete them.


1 Answers

tail can do exactly what you want.

tail -n 10000 file.txt
like image 84
kaylum Avatar answered Sep 21 '22 06:09

kaylum