DomainsFeatured
DomainsFeatured

Reputation: 1506

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.

Upvotes: 8

Views: 1286

Answers (6)

V. Michel
V. Michel

Reputation: 1619

To keep the first 10000 lines :

head -n 10000 file.txt 

To keep the last 10000 lines :

tail -n 10000 file.txt

Test with your file Example

tail -n 3 file.txt
Example Line 3
Example Line 4
Example Line 5

Upvotes: 3

Ed Morton
Ed Morton

Reputation: 203502

$ awk -v n=3 '{a[NR%n]=$0} END{for (i=NR+1;i<=(NR+n);i++) print a[i%n]}' file
Example Line 3
Example Line 4
Example Line 5

Add -i inplace if you have GNU awk and want to do "inplace" editing.

Upvotes: 3

kaylum
kaylum

Reputation: 14046

tail can do exactly what you want.

tail -n 10000 file.txt

Upvotes: 10

hidefromkgb
hidefromkgb

Reputation: 5903

tail -10000 <<<"$(cat file.txt)" > file.txt

Okay, not «just» tail, but this way it`s capable of inplace truncation.

Upvotes: 2

eddiem
eddiem

Reputation: 1030

tac file.txt | sed "$x q" | tac | sponge file.txt

The sponge command is useful here in avoiding an additional temporary file.

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 246807

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

source=file.txt
temp=$(mktemp)
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

Upvotes: 4

Related Questions