VBScript to Replace Text in File

Here is simple and elegant VBScript code to replace plain text in a file with one word with another (poached from http://stackoverflow.com/questions/1975321/find-and-replace-string-in-my-text-with-vbscript):

If WScript.Arguments.Count <> 3 then

WScript.Echo "usage: Find_And_replace.vbs filename word_to_find replace_with "
WScript.Quit
end If

FindAndReplace WScript.Arguments.Item(0), WScript.Arguments.Item(1), WScript.Arguments.Item(2)
WScript.Echo "Operation Complete"

function FindAndReplace(strFilename, strFind, strReplace)
Set inputFile = CreateObject("Scripting.FileSystemObject").OpenTextFile(strFilename, 1)
strInputFile = inputFile.ReadAll
inputFile.Close
Set inputFile = Nothing
Set outputFile = CreateObject("Scripting.FileSystemObject").OpenTextFile(strFilename,2,true)
outputFile.Write Replace(strInputFile, strFind, strReplace)
outputFile.Close
Set outputFile = Nothing
end function

– Soli Deo Gloria

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.