How to Get by Without sed in the Windows Command Line
Today I ran into the need to change some text in a hundred files on a server running Windows.
In linux these tasks are easily solved with sed and the ‘-i’ flag, but on Windows there’s no equivalent of sed.
Had to get creative. First I created the file C:\repl.vbs with this content:
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
objFile.Close
You use it in the command line like this:
cscript C:\repl.vbs `c:\**file_name**.txt` `FOO` `BAR`
This construction replaces FOO with BAR in the file c:\file_name.txt
Armed with this article we process all the files - search for FOO and replace with BAR:
set _find_cmd=findstr /M /P /S /R /I `FOO` *
for /f `tokens=*` %f IN ('%_find_cmd%') DO cscript c:\repl.vbs `%f` `FOO` `BAR`