How do I remove lines of data above a keyword and below a keyword in a text file

Q

Quentin

First off, I would like to thank those who have given me help so far!

I would like to remove all the lines of data above the word Recipe in
a text file and all the lines below the words "End of Recipe" in this
file. I want to keep everything inbetween these two lines. Below is
a small sample of my text file and the code I have so far.

2,3,5,6,56,7,4,7,,,56,5,7,
-1,45,4,451,7,66,7,667,
"Recipe KX009.RCP, Date=02/11/07, Time=12:20:27,
2532,45,23,5,34,52345,,34,5234,345,45
3,34523452,45,3245,245,343443,344,45
,3445,4,45,,26,234,5,24,5145,5,65,56,5
"End of Recipe"
4,5,6,3,7,,8,6,8,68
,67,6,87,6,78,6,76
,243,7,76,9,7,9,6,,


Dim streamR As StreamReader = IO.File.OpenText("c:\MultiTemp1.txt")
Dim streamw As StreamWriter = IO.File.CreateText("c:
\filtered2.txt")
Dim strInput As String

While Not streamR.EndOfStream
strInput = streamR.ReadLine

If strInput.Contains("End") Then
Else
If InStr(strInput, "Recipe", CompareMethod.Text) >= 0
Then
strInput = streamR.ReadLine
streamw.WriteLine(strInput)
End If
End If
End While

streamw.Flush()
streamw.Close()

streamR.Close()

Thanks for your Help!
 
J

Johnny Jörgensen

I realize it's probably not a recognized way of doing things, but when I
have to extract text from a string where I know the start and end
identifier, I normally use the Split function. You can do it in two lines of
code:

Dim TempArray() As String = Split(OriginalString, "Recipe")
ExtractedString = TempArray(1).Substring(0, TempArray(1).Length - 8).Trim


TempArray(0) will contain the text before the first Recipe
TempArray(1) will contain the text between the two Recipe's
TempArray(2) will contain the text after the last Recipe

If both the starting and the ending identifier had been the same, you could
simply have used TempArray(1), but because of the "End of" and the quote
signs, a little more manipulation is needed. You remove the last 8
characters and trim the string (with your example, there will be a space in
the beginning of TempArray(1) ).

Good luck,
Johnny J.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top