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

Jerold Schulman

March 20, 2006

1 Min Read
ITPro Today logo in a gray background | ITPro Today


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

The syntax for using RepInFile.vbs is:

cscript //nologo FolderRepInFile.vbs FileName OldString NewString

Where:

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 ExplicitDim objFSO, objFile, strContentsDim oArgs, FQFN, oTxt, nTxtConst ForReading = 1Const ForWriting = 2Set oArgs = WScript.ArgumentsIf oArgs.Count  3 Then Wscript.Echo "Syntax: cscript //nologo RepInFile.vbs FileName OldString NewString"If oArgs.Count  3 Then Wscript.QuitFQFN = oArgs(0)oTxt = oArgs(1)nTxt = oArgs(2)Set objFSO = CreateObject("Scripting.FileSystemObject")Set objFile = objFSO.OpenTextFile(FQFN, ForReading)strContents = objFile.ReadAllobjFile.CloseIf InStr(strContents, oTxt) ThenstrContents = Replace(strContents, oTxt, nTxt)End IfSet objFile = objFSO.OpenTextFile(FQFN, ForWriting)objFile.Write strContentsobjFile.Close



Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like