I'm using SkipWhile
and TakeWhile
to gather lines from a large file using Linq
.
var foundLines = File.ReadLines(filePath).SkipWhile(line => !line.Contains("pattern1")).TakeWhile(line => !line.Contains("pattern2"));
But I also want the text above the lines I gathered until another string match. Is this possible?
I'll try to show this visually. I only have pattern1
, this variable is given. pattern2
and pattern3
are static data.
...
...
...pattern3...
...
...
...pattern1...
...
...
...pattern2...
...
...
The text between pattern1 and pattern2 is what I can simply catch by doing SkipWhile
and TakeWhile
on File.ReadLines
. After this is catched, I need to go up and catch all data until pattern3
.
So the whole data I want to catch is from pattern3
until pattern2
. But my starting point must be pattern1
because that info (ID) is given and data changes based on that.
For example:
Pattern1
is an ID, or a GUID: KFK284NSKQLOFIE8.
Pattern2
is "end processing"
Pattern3
is "start processing"
And I need all lines between "start processing" and "end processing"
If this is not possible with Linq
, how can I solve this problem? Would FileStream.Seek
be an option?
Try following code. Used code like this for a very long time and I feel is the best method. Each capture is a single string in the List object data. I can modify code to change the format of Data if required.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.txt";
static void Main(string[] args)
{
List<string> data = new List<string>();
StreamReader reader = new StreamReader(FILENAME);
string line = "";
Boolean foundPattern3 = false;
while((line = reader.ReadLine()) != null)
{
if (line.Contains("pattern3"))
{
data.Add(line);
foundPattern3 = true;
}
else
{
if (line.Contains("pattern2"))
{
foundPattern3 = false;
}
else
{
if (foundPattern3)
{
data[data.Count() - 1] += "\n" + line;
}
}
}
}
}
}
}
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.