JSI Tip 10294. How can I replace every occurrence of a string in a file?

I have scripted RepInFile.vbs to replace every occurrence of a string in a file.

The syntax for using RepInFile.vbs is:

cscript //nologo <Drive:>\Folder\RepInFile.vbs FileName OldString NewString


FileName  is the fully qualified path to the file.

OldString is the string you want to replace. Case is respected.

NewString is the replacement for OldString.
RepInFile.vbs contains:
Option Explicit
Dim objFSO, objFile, strContents
Dim oArgs, FQFN, oTxt, nTxt
Const ForReading = 1
Const ForWriting = 2
Set oArgs = WScript.Arguments
If oArgs.Count  3 Then Wscript.Echo "Syntax: cscript //nologo RepInFile.vbs FileName OldString NewString"
If oArgs.Count  3 Then Wscript.Quit
FQFN = oArgs(0)
oTxt = oArgs(1)
nTxt = oArgs(2)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(FQFN, ForReading)
strContents = objFile.ReadAll
If InStr(strContents, oTxt) Then
	strContents = Replace(strContents, oTxt, nTxt)
End If
Set objFile = objFSO.OpenTextFile(FQFN, ForWriting)
objFile.Write strContents

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.