gomasch Development Notes

Montag, September 25, 2006

Batch: Find And Replace Text In A File

I needed to write batch file which also has to replace a string in a text file. Do I admit it took me almost 45min to find a solution? Switching to Powershell will probably ease those small scripting tasks, but right now I want as few dependencies in my windows scripts as possible. Which rules out any Perl, Ruby, Python ... you name it. Batch files (.cmd, .bat), Javascript (.js) and VBScript (.vbs) run out of the box at any Windows XP machine and this is what I need. Boy sometimes it takes literally ages to solve such simple tasks. Solutions:

http://www.motobit.com/tips/detpg_replfile/ 

Microsoft TechNet: How Can I Find and Replace Text in a Text File? :

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.WriteLine strNewText
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 "
Martin 13:27

0 Comments:

Add a comment