Search code examples
c#text-mining

Grab text between two lines


I was just learning and had a problem working with files. I have a method that has two inputs, one at the beginning of the line (lineStart) I want and the other at the end of the line (lineEnd) I need method that extract between these two numbers for me and write on file .

ex ) lineStart = 20 , lineEnd = 90, in output Must be = 21-89 line of txt file.

          string[] lines = File.ReadAllLines(@"");

        int lineStart = 0;
        foreach (string line0 in lines)
        {
            lineStart++;
            if (line0.IndexOf("target1") > -1)
            {
                Console.Write(lineStart + "\n");
            }
        }
           int lineEnd = 0;

         foreach (string line1 in lines)
            {
                lineEnd++;
                if (line1.IndexOf("target2") > -1)
                {
                    Console.Write(lineEnd);
                }
            }

        // method grabText(lineStart,lineEnd){}

enter code here

Solution

  • If your text file is huge, don't read it into memory. Don't look for indexes either, just process it line by line:

    bool writing = false;
    
    using var sw = File.CreateText(@"C:\some\path\to.txt");
    
    foreach(var line in File.ReadLines(...)){ //don't use ReadAllInes, use ReadLines - it's incremental and burns little memory
    
      if(!writing && line.Contains("target1")){
        writing = true; //start writing
        continue; //don't write this line
      }
    
      if(writing){
        if(line.Contains("target2"))
          break; //exit loop without writing this line
        sw.WriteLine(line);
      }
    }