Loukoum Mira
Loukoum Mira

Reputation: 317

Find strings following a pattern in a text file using C#

I'm looking for a way to search through a huge text file and extract a couple of strings that follow a pattern, then to write each of those strings into individual lines in another text file.

Is there an equivalent of Linux grep command, combined with the *, -, ^, [], etc. symbols in C# ?

I hope this is the place for this type of open questions. Thank you !

Upvotes: 1

Views: 4006

Answers (1)

David Arno
David Arno

Reputation: 43264

Firstly, if it's a large file, use File.ReadLines() to scan it as that lazy loads small amounts of data at a time, giving you one line at a time to process.

Then to match the items, you use C#'s regular expression functionality.

You'll likely end up with something like:

var regex = new Regex(-- your match expression --);
foreach (var line in File.ReadLines("someFile").Where(line => regex.Match(line).Success)) 
{
    File.AppendAllText("file to write to", line + Environment.NewLine);
}

Upvotes: 4

Related Questions