adventuresncode
adventuresncode

Reputation: 113

Deleting the rest of the lines in a text file after a line contains a specific string

I have a text file (incoming_orders.log) that is being written to by an api and I need to keep all the orders that come in before a certain time while incoming_orders.log is still being written too.

example of incomimg_orders.log:

OrderId=1,Time=13:02:04,Quantity=7,Part=8

OrderId=2,Time=13:04:47,Quantity=16,Part=1

OrderId=3,Time=13:05:00,Quantity=5,Part=2

OrderId=4,Time=13:05:01,Quantity=86,Part=11

OrderId=5,Time=14:58:04,Quantity=21,Part=19

OrderId=6,Time=14:22:40,Quantity=7,Part=32

OrderId=7,Time=16:15:17,Quantity=7,Part=32

OrderId=8,Time=16:21:23,Quantity=7,Part=32

OrderId=9,Time=16:35:44,Quantity=7,Part=32 ...

I need to get all the orders at or before 13:05:00 and write them to a new file;

I have tried the following, but it only gets rid of OrderId 4 and keeps the rest

string newFile = @"path.log";
string incoming_orders = @"incoming_orders.log"

var oldLines = System.IO.File.ReadAllLines(incoming_orders);
var newLines = oldLines.Where(line => !line.Contains("Time=13:05:01"));

System.IO.File.WriteAllLines(newFile, newLines);

Please let me know what else I can add for clarification.

Thanks

Upvotes: 0

Views: 364

Answers (1)

Troy Gizzi
Troy Gizzi

Reputation: 2519

Change the var newLines... line to this:

var newLines = oldLines.Where(line => line.Split(',')[1].CompareTo("Time=13:05:01") < 0);

Given the sample lines above, that resulted in the following new file content:

OrderId=1,Time=13:02:04,Quantity=7,Part=8
OrderId=2,Time=13:04:47,Quantity=16,Part=1
OrderId=3,Time=13:05:00,Quantity=5,Part=2

Upvotes: 1

Related Questions