简体   繁体   中英

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 !

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM