Reputation: 21
I have a log file (txt file) that i want to read only specific lines from. These lines include a specific set of words followed by number.
For example, the lines that i want to read from the file read:
10:03 Total query took 238.9 mili
10:08 Total query took 659.8 mili
How do I write a code that takes only the time the query
executions took (the mili) and add them up?
I got down the part of reading from the text file only the lines that include "Total query took", but I'm stuck from here
Upvotes: 1
Views: 162
Reputation: 3850
This should be easy with Regular Expression
. I guess the line is on a string.
String str_line = "your line from file" ;
Regex regex = new Regex(@"\d.*");
Match match = regex.Match(str_line);
if (match.Success)
{
//you got the value with "match.Value;"
}
Upvotes: 0
Reputation: 597
public decimal ReadMilliseconds()
{
var lines = File.ReadLines(@"\path\to\file");
decimal totalMilliseconds = 0;
foreach (string line in lines)
{
var match = Regex.Match(line, @"(?<ms>\d*\.?\d*)\s*mili");
if (!match.Success) continue;
decimal value = decimal.Parse(match.Groups["ms"].Value, new CultureInfo("en-US"));
totalMilliseconds += value;
}
return totalMilliseconds;
}
Upvotes: 0
Reputation: 5728
Upvotes: 1