Skip to: Site menu | Main content

Login

Name: 
Password:
Remember me?
Register

Replacing Text in Multiple Text Files

written by Mark Rowlinson - Last updated Oct 2004

Place the following code in a text file and rename it with the extension .vbs. Place all the files you wish to perform the replace on ina single folder. Next, double click on it and give it the folder path containing your text files, the string you wish to search for and the string you wish to replace it with when prompted. That's it!

 
On Error Resume Next 
Dim oFSO 
ReplaceWord 
 
Sub ReplaceWord() 
    Dim x,y,z 
    Dim oFolder, oFile 
    Set oFSO=CreateObject("scripting.filesystemobject") 
    x=trim(inputbox("Enter folder path:")) 
    If x="" Then exit Sub 
    y=trim(inputbox("Enter string to find:")) 
    If y="" Then exit Sub 
    z=trim(inputbox("Enter string to replace:")) 
    If z="" Then exit Sub 
    Set oFolder=oFSO.getfolder(x) 
    If oFolder Is Nothing Then 
        MsgBox "Folder does not exist!" 
    Else 
        For Each oFile In oFolder.files 
            ReplaceInFile(x & "\" & oFile.name) 
        Next 
    End If 
End Sub 
 
Sub ReplaceInFile(strFile,strFind,strReplace) 
    Dim strTemp 
    Set oTxt=oFSO.OpenTextFile(strFile,1) 
    strTemp=oTxt.readall 
    oTxt.close 
    strTemp=replace(strTemp,strFind,strReplace) 
    Set oTxt=oFso.CreateTextFile(strFile,True) 
    oTxt.write(strTemp) 
    oTxt.close 
End Sub