Find string in text file, then move to directory?

I need to write a small app that will read text files looking for a certain string.  When it finds it I need to send that file to a specified directory.  Here is what I have to read the text file:

ifile = FreeFile
Open path & "mantle." & "txt" For Input As ifile
Do While Not EOF(ifile)
 Line Input #ifile, textline

Now what is the best way to search for my strings.  I have approx 20 different strings I need to search for.  Then what would the code be for moving the file to the proper directory?


LVL 1
treyjeffAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

kamallCommented:
Q1. The best way to search for a string in a file is to load the entire file contents into a string variable and search the variable with the InStr() function.

Q2. To move the file to a new dir, use the Name statement.

Regards.
0
kamallCommented:
See the details for the InStr function and the Name statement in the VB help.
0
autCommented:
This code should do what you want. Someone beat me to it as the "proposed answer". aah well. If you like it, tell me, and i'll resubmit it as a proposed answer :-)
-------------------------------

'Declarations
'---------------
    Dim Source As String
    Dim Destination As String
    Dim FileNumber As Integer
    Dim Buffer As String
    Dim CompareString() As String
    Dim NumStrings As Byte
    Dim i As Byte
    Dim flgFound As Boolean
    Dim Pos As Long
    Dim flgError As Boolean
   
    'You can change these values:
    Source = "c:\path\mantle.txt"
    Destination = "c:\newpath\mantle2.txt"
    NumStrings = 20

   
    'Initialize Array
    ReDim CompareString(1 To NumStrings) As String


'1. Load the file into a buffer as follows:
'---------------
    'Load the file into the buffer
    FileNumber = FreeFile
    Open Source For Binary Access Read As FileNumber
    Buffer = Space(LOF(FileNumber))
    Get #1, , Buffer
    Close FileNumber


'2. load the 20 different strings into the array:
'---------------
    CompareString(1) = "ABC"
    CompareString(2) = "XYZ"
    CompareString(3) = "..."


'3. Search for the strings in the file:
'---------------

    For i = 1 To NumStrings
        Pos = 0
        On Error Resume Next
        Pos = InStr(1, Buffer, CompareString(i), vbTextCompare) > 0
        On Error GoTo 0
        If Pos > 0 Then
            flgFound = True
            Exit For
        End If
    Next i
   

'4. Move the file (in effect, it's copy, then delete):
'---------------
    If flgFound Then
        On Error GoTo ErrorHandler
        FileCopy Source, Destination
        On Error GoTo 0
        If flgError Then Kill Source
    End If



'At the end of the subroutine, paste these lines:
Exit Sub

ErrorHandler:
    flgError = True
    Resume Next
0
The Ultimate Tool Kit for Technolgy Solution Provi

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy for valuable how-to assets including sample agreements, checklists, flowcharts, and more!

autCommented:
Oops, the line:

If flgError Then Kill Source

should be:

If Not flgError Then Kill Source

0
treyjeffAuthor Commented:
Ok, I have about 100 files to go through, how can it be changed to work with that?  I probably have to change this:

Source = "c:\path\mantle.txt"    Destination = "c:\newpath\mantle2.txt"

0
autCommented:
I modified the code for you...

First, paste this line in the declarations area of the form:

Dim CompareString() As String


'Then from your code, you have to call this function only once to initialize the strings array.
'When you call it, the argument named "NumStrings" will define the number of strings to be searched for.
'For example call it like this:
'    InitializeStringsArray 20

Private Sub InitializeStringsArray(NumStrings As Byte)
    ReDim CompareString(1 To NumStrings) As String

    'Load the 20 different strings into the array:
    '---------------
    CompareString(1) = "ABC"
    CompareString(2) = "XYZ"
    CompareString(3) = "..."
    'and so on
End Sub


'Finally, call this function as many times as you need. Each time, specify the "Source" and "Destination".
Private Function FindAndMove(Source As String, Destination As String) As Boolean
    'Declarations
    '---------------
    Dim FileNumber As Integer
    Dim Buffer As String
    Dim NumStrings As Byte
    Dim i As Byte
    Dim flgFound As Boolean
    Dim Pos As Long
     
    On Error GoTo ErrorHandler
    '1. Load the file into a buffer as follows:
    '---------------
    'Load the file into the buffer
    FileNumber = FreeFile
    Open Source For Binary Access Read As FileNumber
    Buffer = Space(LOF(FileNumber))
    Get #1, , Buffer
    Close FileNumber


    '2. Search for the strings in the file:
    '---------------
    NumStrings = UBound(CompareString)

    For i = 1 To NumStrings
        Pos = 0
        On Error Resume Next
        Pos = InStr(1, Buffer, CompareString(i), vbTextCompare) > 0
        On Error GoTo 0
        If Pos > 0 Then
            flgFound = True
            Exit For
        End If
    Next i
   

    '3. Move the file:
    '---------------
    Name Source As Destination

    FindAndMove = True
ErrorHandler:
End Function

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
treyjeffAuthor Commented:
I have put that code into the project.  I want to be able to select the source directory at start up.  Also, each different array element goes to a different directory.  So if I find voucher it has to go to say the windows/voucher directory.  Can these be done?
0
autCommented:
I did not understand what you want to do exactly. Please explain what you're trying to do in detail, and I can help you with it.
0
treyjeffAuthor Commented:
For the source directoy it should always be the same but it also may not. I there a way I can select the directory which to process.  All the text files to be processed come from Unix and I dump them to one directory.  I want to be able to select it just in case someone stores them in another directory.  Also, the 20 different things I'm searching for need to go to different directories.  So all the ones in array(0) ned to go to a directory, array(1) to another etc.  Also, Iwould really like this program to process every text file in the source directory, is this all possible?  I have raised the points once and will again if need be.
0
autCommented:
So, basically, I'll do the following right now:
(a) Change the function so that it accepts just a source directory.

(b) Process every single .TXT file in the source directory.

(c) Move the files based on the found strings...

This will be no problem. I think it would be good time to raise the points a little more ;-)
0
treyjeffAuthor Commented:
I have raised the points by 125 today.  Also, the files are not all .txt  They are .spl but they are all text.  That is just the extension on them.
0
autCommented:
Ok, here's the code you need:
------------------------------



'Put these in the declarations section
Dim CompareString() As String
Dim DestinationFolder() As String


'From your code, you have to call this subroutine only once to
'initialize the destination folders array. When you call it,
'the argument named "NumStrings" will define the number of
'destination folders available
'Note: NumStrings should be the same as NumStrings in the
'InitializeStringsArray subroutine

'For example call it like this:
'    InitializeDestinationFolders 20
Private Sub InitializeDestinationFolders(NumStrings As Byte)
    Dim i As Byte
   
    ReDim DestinationFolder(1 To NumStrings) As String

    'Specify the 20 different destination folders here
    '---------------
    DestinationFolder(1) = "c:\folder1"
    DestinationFolder(2) = "c:\folder2"
    DestinationFolder(3) = "..."
    'and so on


    'Ensure that all destination folders have trailing
    'backslashes
    For i = 1 To NumStrings
        If Not (Right(DestinationFolder(i), 1) = "\") Then DestinationFolder(i) = DestinationFolder(i) + "\"
    Next i
End Sub


'From your code, you have to call this subroutine only once to
'initialize the strings array. When you call it, the argument
'named "NumStrings" will define the number of strings to be
'searched for.
'Note: NumStrings should be the same as NumStrings in the
'InitializeDestinationFolders subroutine

'For example call it like this:
'    InitializeStringsArray 20
Private Sub InitializeStringsArray(NumStrings As Byte)
    ReDim CompareString(1 To NumStrings) As String

    'Load the 20 different strings into the array:
    '---------------
    CompareString(1) = "ABC"
    CompareString(2) = "XYZ"
    CompareString(3) = "..."
   
    'and so on

End Sub


'Finally, call this function as many times as you need.
'Each time, specify the "SourceFolder". The function will
'process every single text file it enounters in that folder,
'and move them based on the found string
Private Function FindAndMove(SourceFolder As String)
    'Declarations
    '---------------
    Dim FileNumber As Integer
    Dim CurrentFile As String
    Dim Buffer As String
    Dim NumStrings As Byte
    Dim i As Byte
    Dim flgFound As Boolean
    Dim Pos As Long
   
    'Initialize
    On Error GoTo ErrorHandler
    NumStrings = UBound(CompareString)
   
    'Add trailing backslash to SourceFolder
    If Not Right(SourceFolder, 1) = "\" Then SourceFolder = SourceFolder & "\"
   
    'Find first text file file in source folder
    CurrentFile = Dir(SourceFolder & "*.spl")
   
    'Loop for each .SPL file in the folder (directory)
    Do While Len(CurrentFile) > 0
   
        '1. Load the current file into a buffer as follows:
        '---------------
        FileNumber = FreeFile
        Open SourceFolder & CurrentFile For Binary Access Read As FileNumber
        Buffer = Space(LOF(FileNumber))
        Get #1, , Buffer
        Close FileNumber
   
   
        '2. Search for the strings in the current file
        '---------------
        For i = 1 To NumStrings
            Pos = InStr(1, Buffer, CompareString(i), vbTextCompare)
            If Pos > 0 Then
                'Found a string, moving file to destination
                Name SourceFolder & CurrentFile As DestinationFolder(i) & CurrentFile
                flgFound = True
                Exit For
            End If
        Next i
   
        'Find Next File
        CurrentFile = Dir
    Loop

    FindAndMove = True
ErrorHandler:
End Function

0
treyjeffAuthor Commented:
I'm getting erros all over the place.  Could I send you a zip of the files I have and source I've written.  It's all very small.
0
autCommented:
go ahead. aut@usa.net
Increase points though.
0
kamallCommented:
>> I think it would be good time to raise the points a little more!!!
>>go ahead... Increase points though!!!
Is this help or kind of .....???
0
autCommented:
Kamall,
some kind of what? The question was at 50 points when it was asked, treyjeff wants specific code to be written for him, and not just help. I thought the question deserved to be of "moderate" difficulty, that's all...
0
treyjeffAuthor Commented:
I agree, it's gone back and forth a couple of times.
0
treyjeffAuthor Commented:
Well, I have the files but the person it's being written for says it doesn't work?
0
autCommented:
Probably it's not configured right on his/her PC?
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic Classic

From novice to tech pro — start learning today.