Thursday, November 12, 2015

find and replace text in a file use batch file command line

Create file replace.vbs:
Const ForReading = 1    
Const ForWriting = 2

strFileName = Wscript.Arguments(0)
strOldText = Wscript.Arguments(1)
strNewText = Wscript.Arguments(2)

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFileName, ForReading)
strText = objFile.ReadAll
objFile.Close

strNewText = Replace(strText, strOldText, strNewText)
Set objFile = objFSO.OpenTextFile(strFileName, ForWriting)
objFile.Write strNewText  'WriteLine adds extra CR/LF
objFile.Close
To use this revised script (which we’ll call replace.vbs) just type a command similar to this from the command prompt:
cscript replace.vbs "C:\Scripts\Text.txt" "Jim " "James "

No comments: