Parsing a txt file

Da moe
05-23-2003, 10:09 AM
Hello All :)

I have simple code to search for certain txt in a txt file using a module for excel

Open "infile.txt" For Input As #1
Open "output.txt" For Output As #2
TextToFind = "xxxx"
Do Until EOF(1)
Line Input #1, data
If InStr(1, data, TextToFind) Then
Print #2, data
End If
Loop
Close
End Sub

How could i code to when "xxxx" is found, it also takes the line of text above it.(or all the text data until is reaches a null line in the text file) So below i have txt at aaa. bbb. ccc. ddd. when i run the code above it outputs bbbbbbbb- xxxxxx & ddddd - xxxxxx since "xxxx" is the text i am looking for.. but how do i also caputure the txt aaaaa, & ccccc, since it is related to the text files i have. Is there a way to search for "xxxx" and when found, it takes all the text until it finds a break, or space between each group of txt files?

aaaaaaaaa
bbbbbbbbb - xxxxxx
ccccccccc
ddddddddd - xxxxxxx

eeeeee
fffffffff - xxxxxx
gggggg
hhhhhh - xxxxxxx

hehe, hope that makes sense
Thanks :)

BankCop
05-23-2003, 01:06 PM
what about when you may have two lines adjacent?

aaaaaaa
bbbbbbb xxxxx
ccccccc xxxxx
ddddddd

GavinO
05-24-2003, 02:40 PM
Just track the last line in another string. So at the end of the loop you have lastline$=data, and instead of Print #2,data you have Print #2,lastline$.

pinster
05-26-2003, 02:44 AM
my suggestion would be to read the file as a whole and split it into an array. Then do your searching onto the array. If found the xxxx, you minus the current index by 1 and get the above text aaaa also.


Private Sub Form_Load()
Dim data() As String
Dim ff As Integer
Dim file As String
Dim i As Integer
Dim keyword As String

keyword = "xxxxx"
ff = FreeFile
Open "C:\data.txt" For Input As #ff
file = Input$(LOF(ff), ff)
Close #ff
data = Split(file, vbCrLf)
For i = 0 To UBound(data)
If InStr(1, data(i), keyword) Then
Debug.Print data(i - 1) & vbCrLf & data(i)
End If
Next i
MsgBox "Operation Done"

End Sub

Da moe
05-26-2003, 11:24 AM
Thanks Guys!!! :)

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum