Solved

VB file search and Replace

Posted on 1998-09-09
11
338 Views
Last Modified: 2012-05-04
I want a procedure that will search and replace strings in a text file.

I want this to happen using VB
Is there a dll or activeX dll that allready does this?

eg.
Public Sub SearchAndReplace(pstrFindThis as string, pstrReplaceWithThis as string, pstrFilename as string)

any help appreciated
0
Comment
Question by:pcrimm
  • 6
  • 4
11 Comments
 
LVL 4

Expert Comment

by:mcix
ID: 1433819
I have a function that does that...

If you want it, I will e-mail you the source.
0
 

Author Comment

by:pcrimm
ID: 1433820
I would greatly appreciate that.
pcrimm@optum.com
0
 
LVL 14

Accepted Solution

by:
waty earned 180 total points
ID: 1433821
HEre is code. If you want, I can create the full function :

You could use the following code :

dim sTmp     as string
dim sSgmlIn  as string

' *** Open the file to read all the text file
nSgmlIn = FreeFile
Open sSgmlCurrent For Input Access Read As #nSgmlIn
sSgmlIn = ""
Do While EOF(nSgmlIn) = False
   Line Input #nSgmlIn, sTmp
   sSgmlIn = sSgmlIn & sTmp
Loop
Close #nSgmlIn

sTmp = ReplaceString(sSgmlIn, pstrFindThis, pstrReplaceWithThis)

nPrintOut = FreeFile
Open sPSOut For Binary Access Write As #nPrintOut
Write #nPrintOut, , sTmp
close #nPrintOut


Function ReplaceString(sSearch As String, sSearchFor As String, sReplaceWith As String) As String
   ' *** Searches the sSearch variable for sSearchFor
   ' *** and replaces it with sReplaceWith.

   On Error GoTo ERROR__ReplaceString

   Dim lFoundLoc        As Long   ' Location of match.
   Dim lLenRemove       As Long   ' Length of string being replaced.
   
   ' *** Set length of original text to skip.
   lLenRemove = Len(sSearchFor)    ' Set location of match.
   
   lFoundLoc = InStr(1, sSearch, sSearchFor)
   
   ' If sSearchFor isn't found in sSearch
   ' just return the original string.
   If lFoundLoc = 0 Then
      ReplaceString = sSearch
      ' If match is found, return original string up to match
      ' location, concatenate new text, and search the rest of
      ' the string recursively for additional matches.
   Else
      ReplaceString = left(sSearch, lFoundLoc - 1) & sReplaceWith & ReplaceString(Mid(sSearch, lFoundLoc + lLenRemove), sSearchFor, sReplaceWith)
   End If

EXIT_ReplaceString:
   Exit Function

ERROR__ReplaceString:
   ' Print error to Debug window and don't interrupt query.
   Debug.Print "Error Replacing String """ & sSearchFor & """ with """ & sReplaceWith & """ in text """ & sSearch & """"
   ' If there is an error, return original string
   ' and exit the function.        ReplaceString = sSearch
   Resume EXIT_ReplaceString

End Function

0
 
LVL 14

Expert Comment

by:waty
ID: 1433822
Here is the complete function
Function FileReplaceString(sFile As String, sSearchFor As String, sReplaceWith As String) As Boolean
   ' *** Searches in sFile file for sSearchFor
   ' *** and replaces it with sReplaceWith.

   Dim nFile      As Integer
   
   Dim sTmp       As String
   Dim sText      As String
   
   On Error GoTo ERROR_FileReplaceString
   
   ' *** Open the file to read all the text file
   nFile = FreeFile
   Open sFile For Input Access Read As #nFile
   sText = ""
   Do While EOF(nFile) = False
      Line Input #nFile, sTmp
      sText = sText & sTmp
   Loop
   Close #nFile
   
   ' *** Replace the text
   sTmp = ReplaceString(sText, sSearchFor, sReplaceWith)
   
   ' *** Delete the previous file
   Kill sFile
   
   ' *** Save as temporary
   nFile = FreeFile
   Open sFile For Binary Access Write As #nFile
   Write #nFile, , sTmp
   Close #nFile

   FileReplaceString = True
   Exit Function

ERROR_FileReplaceString:
   FileReplaceString = False
   
   Exit Function

End Function


Function ReplaceString(sSearch As String, sSearchFor As String, sReplaceWith As String) As String
   ' *** Searches the sSearch variable for sSearchFor
   ' *** and replaces it with sReplaceWith.

   On Error GoTo ERROR__ReplaceString

   Dim lFoundLoc        As Long   ' Location of match.
   Dim lLenRemove       As Long   ' Length of string being replaced.
   
   ' *** Set length of original text to skip.
   lLenRemove = Len(sSearchFor)    ' Set location of match.
   
   lFoundLoc = InStr(1, sSearch, sSearchFor)
   
   ' If sSearchFor isn't found in sSearch
   ' just return the original string.
   If lFoundLoc = 0 Then
      ReplaceString = sSearch
      ' If match is found, return original string up to match
      ' location, concatenate new text, and search the rest of
      ' the string recursively for additional matches.
   Else
      ReplaceString = left(sSearch, lFoundLoc - 1) & sReplaceWith & ReplaceString(Mid(sSearch, lFoundLoc + lLenRemove), sSearchFor, sReplaceWith)
   End If

EXIT_ReplaceString:
   Exit Function

ERROR__ReplaceString:
   ' Print error to Debug window and don't interrupt query.
   Debug.Print "Error Replacing String """ & sSearchFor & """ with """ & sReplaceWith & """ in text """ & sSearch & """"
   ' If there is an error, return original string
   ' and exit the function.        ReplaceString = sSearch
   Resume EXIT_ReplaceString

End Function
0
 

Author Comment

by:pcrimm
ID: 1433823
Here is my curriosity.
I am not interested in the logistics of searching and replacing.(I am cool with that)
I AM troubled by the fact you can not open a file, muck with it(ie search, replace, go back to the top, navigate, write a few lines here, a few characters there), and then close it.
What is this open, read, kill, recreate? (not you Wady, VB)
SPEED is necessary
many files, many large files,
which brings a problem to Wady's proposal (cant do the loop with large files)

I want to open a file, find the search, change it, then close it

I understand you could input line by line, while searching each line and then add the new line to a temp file, but why cant you go back and delete a line you found in the open file that had the search string in it?

Otherwise I am reluctantly willing to create a component in C++ that will do the job and use that in vb. (but has that allready been done?)

I need a therapist, anyone?????
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 14

Expert Comment

by:waty
ID: 1433824
You could read the file at one time

' *** Open the file to read all the text file
nFile = FreeFile
Open sFile For Input As #nFile
sText = InputB(FileLen(sFile), nFile)
Close #nFile

0
 

Author Comment

by:pcrimm
ID: 1433825
Waty, the problem is, a text file the size of 2 megs will die if you try to load it into a vb string.
Performance on the machine will suffer.
And I would still have to write the entire changed string to another file.(Because the end result is to change the contents of the file.)
0
 
LVL 14

Expert Comment

by:waty
ID: 1433826
Ok.
You could not change the same file when you are reading it.

The solution is that you open the input file, open an output file using a temporary name, read by 32k, replace string in all those 32k, write this in the output file. When all the input file is done, copy the temporary over the input file.


0
 
LVL 14

Expert Comment

by:waty
ID: 1433827
Ok.
You could not change the same file when you are reading it.

The solution is that you open the input file, open an output file using a temporary name, read by 32k, replace string in all those 32k, write this in the output file. When all the input file is done, copy the temporary over the input file.

If you want, I can write this for you.

0
 

Author Comment

by:pcrimm
ID: 1433828
Waty, Post the code and the spoils are yours.
I truely appreciate your help

Yours,
Paul
0
 
LVL 14

Expert Comment

by:waty
ID: 1433829
Here is the code

Use the function defines in previous comments, and add those two funtions :

Private Declare Function GetTempPathA Lib "kernel32" (ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long
Private Declare Function GetTempFileNameA Lib "kernel32" (ByVal lpszPath As String, ByVal lpPrefixString As String, ByVal wUnique As Long, ByVal lpTempFileName As String) As Long
Private Const UNIQUE_NAME = &H0

Public Function GetTempFileName() As String
   ' *** Returns a unique tempfile name.
   
   Dim sTmp    As String
   Dim sTmp2   As String
   
   sTmp2 = GetTempPath
   sTmp = Space(Len(sTmp2) + 256)
   Call GetTempFileNameA(sTmp2, App.EXEName, UNIQUE_NAME, sTmp)
   GetTempFileName = Left$(sTmp, InStr(sTmp, Chr$(0)) - 1)

End Function

Public Function GetTempPath() As String
   ' *** Returns the path to the temp directory.
     
   Dim sTmp       As String
   Dim i          As Integer
   
   i = GetTempPathA(0, "")
   sTmp = Space(i)
   
   Call GetTempPathA(i, sTmp)
   GetTempPath = AddBackslash(Left$(sTmp, i - 1))

End Function


Function FileReplaceString(sFileIn As String, sSearchFor As String, sReplaceWith As String) As Boolean
   ' *** Searches in sFile file for sSearchFor
   ' *** and replaces it with sReplaceWith.

   Dim nFileIn    As Integer
   Dim nFileOut   As Integer
   
   Dim sFileOut   As String
   
   Dim sTmp       As String
   Dim sText      As String
   
   Dim nMax       As Long
   Dim nCount     As Long
   
   On Error GoTo ERROR_FileReplaceString
   
   sFileOut = GetTempFileName()
   
   ' *** Get the maximum size
   nMax = FileLen(sFileIn)
   
   If (nMax > 32000) Then
      nCount = 32000
   Else
      nCount = nMax
      nMax = nMax - nCount
   End If
   
   ' *** Open the file to read all the text file
   nFileIn = FreeFile
   Open sFileIn For Input As #nFileIn
   
   ' *** Save as temporary
   nFileOut = FreeFile
   Open sFileOut For Output As #nFileOut
   
   sText = ""
   Do While EOF(nFileIn) = False
      sTmp = Input(nCount, #nFileIn)
      sText = ReplaceString(sTmp, sSearchFor, sReplaceWith)
      Write #nFileOut, , sText
     
      If (nMax > 32000) Then
         nCount = 32000
      Else
         nCount = nMax
         nMax = nMax - nCount
      End If
   
   Loop
   Close #nFileIn
   Close #nFileOut

   ' *** Copy the temporary to the original
   FileCopy sFileOut, sFileIn
   
   ' *** Delete the temporary file
   Kill sFileOut
   
   FileReplaceString = True
   Exit Function

ERROR_FileReplaceString:
   If (Len(sFileOut) > 0) Then Kill sFileOut
   
   FileReplaceString = False
   
   Exit Function

End Function

0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

There are many ways to remove duplicate entries in an SQL or Access database. Most make you temporarily insert an ID field, make a temp table and copy data back and forth, and/or are slow. Here is an easy way in VB6 using ADO to remove duplicate row…
Article by: Martin
Here are a few simple, working, games that you can use as-is or as the basis for your own games. Tic-Tac-Toe This is one of the simplest of all games.   The game allows for a choice of who goes first and keeps track of the number of wins for…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…

708 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

16 Experts available now in Live!

Get 1:1 Help Now