Search code examples
c#linq

Counting number of lines with occurrence of specific word


I am trying to count number of lines in a text file that contain a specific word "uniqueId".

I used the following code but always get 0 where I can count about 1000+ occurrences.

var total = 0;
char[] delimiters = new[] { '\r', '\n' };

using (StreamReader sr = new StreamReader(fi.FullName))
{
    while (!sr.EndOfStream)
    {
        var counts = sr
            .ReadLine()
            .Split(delimiters, StringSplitOptions.RemoveEmptyEntries)
            .GroupBy(s => s)
            .Select(g => new { Word = g.Key, Count = g.Count() });
        var wc = counts.SingleOrDefault(c => c.Word == "uniqueId");
        total += (wc == null) ? 0 : wc.Count;
    }
}

Sample text file entry:

2023-07-31 07:26:35.211|Message sent (value: '{"uniqueId":1527258,"Node":"13","lclDtm":"2023-07-31T07:18:38.803","utcDtm":"2023-07-31T11:18:38.803","errorCode":"E45"}'). Delivery status: Persisted; Partition: 1; Offset: 161454; Created (UTC): 7/31/2023 11:26:34 AM

2023-07-31 07:26:35.648|Message sent (value: '{"uniqueId":1527291,"Node":"13","lclDtm":"2023-07-31T07:19:15.444","utcDtm":"2023-07-31T11:19:15.444","errorCode":"E45"}'). Delivery status: Persisted; Partition: 1; Offset: 161455; Created (UTC): 7/31/2023 11:26:35 AM

Solution

  • Count on RegEx for problems like this. A one liner example:

    int count = File.ReadLines(fi.FullName).Count(line => Regex.IsMatch(line, "uniqueId"));