Solved

Routine to search text files and list the file found and the lines the matches are found on.

Posted on 2004-10-06
5
140 Views
Last Modified: 2010-05-02
Hi
I need help from the Guru's!
I have a lot of text files and I need to be able to do a text file search for matching words or phrases.

I need to list the names of the files where matches were found along with the contents of the line where the match was found. Like this:

Search term: Holiday

File1.txt
Line 23: it was time for a holiday with the staff
Line 340:  Arnold said he needed a holiday

File2.txt
Line 72: We all need a holiday!

End of Search

Could anyone point me to a (preferably vb script) routine or code for this?

Thank you!

Ted
0
Comment
Question by:tcalbaz
5 Comments
 
LVL 26

Expert Comment

by:EDDYKT
ID: 12240244
Try this

Option Explicit

Private Sub Command1_Click()

End Sub
Private Sub Readfile(ByVal Filename As String, ByVal matchstring As String)
    Dim ff As Integer, s As String, arr, i As Long
       
    ff = FreeFile
    Open Filename For Binary Access Read Lock Read Write As #ff
    s = Space$(LOF(ff))
    Get #ff, , s
    Close ff
   
    Debug.Print Filename
    arr = Split(s, vbCrLf)
    For i = 1 To UBound(arr)
        If (InStr(1, ucase(arr(i - 1)), ucase(matchstring))) Then
            Debug.Print "Line " & i + 1 & ": " & arr(i - 1)
        End If
    Next
   
    Erase arr
End Sub
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 12240568
Create a new project and add a class.  To the form, add a commandbutton, label and a textbox.  For the textbox, set the MultiLine property to true and the Scrollbars property to 3 (both).  Paste the code below into the appropriate area as labeled:

Change the call to the searchFiles sub in Command1_Click to meet your needs.

Regards,

Idle_Mind

' --------------------------------------------------------
' Class1
' --------------------------------------------------------
Public fileName As String
Public lineNumbers As Collection
Public lines As Collection

Private Sub Class_Initialize()
    Set lineNumbers = New Collection
    Set lines = New Collection
End Sub

' --------------------------------------------------------
' Form1
' --------------------------------------------------------
Option Explicit

Private matches As Collection

Private Sub Form_Load()
    Label1.Caption = ""
End Sub

Private Sub Command1_Click()
    Dim match As Class1
    Dim lineNumber As Variant
   
    Set matches = New Collection
    searchFiles "C:\Documents and Settings\Michael\My Documents\1 VB Code\", "*.txt", "test"
    Text1.Text = ""
    For Each match In matches
        Text1.Text = Text1.Text & match.fileName & vbCrLf
        For Each lineNumber In match.lineNumbers
            Text1.Text = Text1.Text & "Line " & lineNumber & ": " & match.lines.Item(CStr(lineNumber)) & vbCrLf
        Next
        Text1.Text = Text1.Text & vbCrLf
    Next
    Label1.Caption = matches.Count & " file(s) with matches found"
End Sub

Private Sub searchFiles(ByVal basePath As String, ByVal filter As String, ByVal value As String)
    Dim curFile As String
    Dim subdir As Variant
    Dim subDirs As Collection
    Dim ff As Integer
    Dim inputLine As String
    Dim lineNumber As Long
    Dim match As Class1
   
    curFile = Dir(basePath & filter)
    Do While curFile <> ""
        Label1.Caption = basePath & curFile
        Set match = Nothing
        lineNumber = 0
        ff = FreeFile
        Open basePath & curFile For Input As #ff
        While Not EOF(ff)
            lineNumber = lineNumber + 1
            Line Input #ff, inputLine
            If InStr(LCase(inputLine), LCase(value)) > 0 Then
                If match Is Nothing Then
                    Set match = New Class1
                    match.fileName = basePath & curFile
                End If
                match.lineNumbers.Add lineNumber
                match.lines.Add inputLine, CStr(lineNumber)
            End If
            DoEvents
        Wend
        Close #ff
        If Not (match Is Nothing) Then
            matches.Add match
        End If
       
        DoEvents
        curFile = Dir()
    Loop
   
    ' build subDirs collection
    Set subDirs = New Collection
    curFile = Dir(basePath, vbDirectory)
    Do
        If curFile <> "" Then
            If (GetAttr(basePath & curFile) And vbDirectory) = vbDirectory Then
                If curFile <> "." And curFile <> ".." Then
                    subDirs.Add basePath & curFile & "\"
                End If
            End If
        End If
        DoEvents
        curFile = Dir()
    Loop While curFile <> ""
   
    ' recurse into each subdir
    For Each subdir In subDirs
        searchFiles subdir, filter, value
    Next
End Sub
0
 
LVL 6

Accepted Solution

by:
SCDMETA earned 500 total points
ID: 12256124

I realize you are asking for code to do this...
but just in case you are trying to code your way out of a tedious task I thought I would point you towards the following program.  It allows standard and regular expression search, replace, etc across multiple files.

http://www.wingrep.com/
0
 
LVL 1

Author Comment

by:tcalbaz
ID: 12300669
SCDMETA  

This is the answer which proves most useful.

Thank you

Ted
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 12300787
< Sighs >

>> Could anyone point me to a (preferably vb script) routine or code for this?

For future reference tcalbaz...

If you are going to ask a question in a PROGRAMMING topic area asking for code, then at least give those who gave you actual code some Assist points if you accept a non coding solution.

No offense meant to SCDMETA as WinGrep looks like a great utitlity.

=)

~IM
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction I needed to skip over some file processing within a For...Next loop in some old production code and wished that VB (classic) had a statement that would drop down to the end of the current iteration, bypassing the statements that were c…
Introduction While answering a recent question about filtering a custom class collection, I realized that this could be accomplished with very little code by using the ScriptControl (SC) library.  This article will introduce you to the SC library a…
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now