Replace.vbs

Find and replace a text string in a file.

'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 

Example

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:

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 SS64.com 1999-2014
Some rights reserved