How-to: Find and replace a text string in a file [Replace.vbs]

Before running any global find and replace - make a backup. It is very easy to match and replace text you didn't intend!

'usage: cscript replace.vbs Filename "StringToFind" "stringToReplace"
 
Option Explicit
Dim fso,strFilename,strSearch,strReplace,objFile,oldContent,newContent
 
strFilename=WScript.Arguments.Item(0)
strSearch=WScript.Arguments.Item(1)
strReplace=WScript.Arguments.Item(2)
 
'Does file exist?
Set fso=CreateObject("Scripting.FileSystemObject")
if fso.FileExists(strFilename)=false then
   wscript.echo "file not found!"
   wscript.Quit
end if
 
'Read file
set objFile=fso.OpenTextFile(strFilename,1)
oldContent=objFile.ReadAll
 
'Write file
newContent=replace(oldContent,strSearch,strReplace,1,-1,0)
set objFile=fso.OpenTextFile(strFilename,2)
objFile.Write newContent
objFile.Close 

Examples

cscript //Nologo replace.vbs c:\docs\demo.txt "Madonna" "Lady Gaga"

“Substitute “damn” every time you're inclined to write “very;” your editor will delete it and the writing will be just as it should be” ~ Mark Twain

Related VBScript commands

replace - Find and replace text in a string.
Repl.bat - FInd and Replace text, JScript/Batch script
FindRepl.bat - FInd and Replace text, JScript/Batch script.


 
Copyright © 1999-2024 SS64.com
Some rights reserved