1

How do I replace text from one file with text from another file using vbscript?

The text being replaced is somewhere in the middle of the file.

1
  • Throw us a bone. An example would be very useful. Commented Nov 11, 2008 at 14:58

2 Answers 2

4

filea.txt: hello cruel world

fileb.txt: cruel

filec.txt: happy

will make sResult = "hello happy world" after the following has executed.

Dim oFSO
Dim sFileAContents
Dim sFileBContents
Dim sFileCContents
Dim sResult
Set oFSO = CreateObject("Scripting.FileSystemObject")
sFileAContents = oFSO.OpenTextFile("c:\filea.txt").ReadAll()
sFileBContents = oFSO.OpenTextFile("c:\fileb.txt").ReadAll()
sFileCContents = oFSO.OpenTextFile("c:\filec.txt").ReadAll()
sResult = Replace(sFileAContents, sFileBContents, "")
Sign up to request clarification or add additional context in comments.

Comments

0

FileToSearch is the file with the text you want to search for replacement
FileReplaceText is the file containing the replacement text

Edit the value of the variable strTextToFind to contain the text you are searching for and replacing

Dim objFSO
Dim strFileToSearch
Dim strFileReplaceText

Dim strTextToFind
Dim strTextToSearch
Dim strTextReplaceText
Dim strFinalText

    strFileToSearch = "C:\FileToSearch.txt"
    strFileReplaceText = "C:\FileReplaceText.txt"

    strTextToFind = "text to search for here"

    Set objFSO = CreateObject("Scripting.FileSystemObject")  
    strTextToSearch = objFSO.OpenTextFile(strFileToSearch).ReadAll()  
    strFileReplaceText = objFSO.OpenTextFile(strFileReplaceText).ReadAll()  

    strFinalText = Replace(strTextToSearch, strTextToFind, strFileReplaceText)  

If you want to write this final text back out to a file then add this code:

Const ForWriting = 2
Dim strFileFinalOutput

    strFileFinalOutput = "C:\FileFinalOutput.txt"

    Set objTextFile = objFSO.OpenTextFile(strFileFinalOutput, ForWriting, True)
    objTextFile.Write strFinalText
    objTextFile.Close
    Set objTextFile = Nothing

This code reads the entire file into memory (.ReadAll) and may experience problems with very large files. In this case, the code can be edited to read/search/replace/write the data line by line.

If the text you are searching for is not continuous and all on the same line then the search/replace process is more involded and this code will need additional work to handle it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.