How to replace text from one file with text from another file using vbscript?

How to replace text from one file with text from another file using vbscript?

The text to replace is somewhere in the middle of the file.

+1


source to share


2 answers


filea.txt: hello cruel world

fileb.txt: cruel

filec.txt: happy



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

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, "")

      

+4


source


FileToSearch is the text file you want to find to replace
FileReplaceText is the file containing the replacement text

Change the value of the strTextToFind variable to contain the text you are looking for and replace

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 to the file, add the following 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 there may be a problem with very large files. In this case, the code can be edited to read / find / replace / write data line by line.

If the text you are looking for is not contiguous and everything is on one line, then the find / replace process is more superimposed and more work will be required for this code.

0


source







All Articles