This script is useful if you want to replace a certain string only in files with a specific extension. In this tutorial we will replace a string “Replace Me” with “This is replaced” only in files that have the “.txt” and “.csv” extensions, and another string “Hello” with “Bye” in files that only have “.vbs” extension.
The code is as follows:
Const ForReading = 1 Const ForAppending = 2 Dim FileName, search_repl, search_find, search_find2, path_into_search path_into_search = "C:\Users\user\Desktop\Tests" search_find = "Replace Me" search_find2 = "Hello" search_repl = "This is replaced" search_repl2 = "Bye" set FSO = createobject("Scripting.FileSystemObject") set folder = FSO.getfolder(path_into_search) for each file in folder.files Filename = folder & "\" & file.name if lcase(right(Filename,3))="txt" OR lcase(right(Filename,3))="csv" then Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile (FileName, ForReading) strText= objFile.ReadAll objFile.Close strText=replace(strText,search_find,search_repl,1,-1,1) Set objTextFilen = objFSO.OpenTextFile(FileName, ForAppending, True) objTextFilen.Write(strText) objTextFilen.Close End If if lcase(right(Filename,3))="vbs" then Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile (FileName, ForReading) strText= objFile.ReadAll objFile.Close strText=replace(strText,search_find2,search_repl2,1,-1,1) Set objTextFilen = objFSO.OpenTextFile(FileName, ForAppending, True) objTextFilen.Write(strText) objTextFilen.Close End If Next