Replacing text in a file

Anything VBScript-related, including Windows Script Host, WMI, ADSI, and more.
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
Locked
User avatar
EBrant
Posts: 99
Joined: Thu Feb 02, 2012 1:51 am

Replacing text in a file

Post by EBrant » Tue Sep 11, 2012 11:32 pm

Hello All :)

I have the following little script

Const ForReading = 1
Const ForWriting = 2

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

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strDirectoryName)
Set objFiles = objFolder.Files

For each folderIdx In objFiles

Set objFile = objFSO.OpenTextFile(folderIdx.path, ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, strOldText, strNewText)
Set objFile = objFSO.OpenTextFile(folderIdx.path, ForWriting)
objFile.WriteLine strNewText
objFile.Close

next

It is meant to read in the file names from a directory, then search and replace a given string in each file. It kind of works, the issue is it places to contents of the first file (following the replacement) into the second file and the content of the first and second file into the third file and so on. Which is not what I want, the original file should only contain its own content (with the string replaced of course)

I am thinking the next is in the wrong place or I need to clear the contents of the strNewText variable (but cannot see why if the next is in the correct place.

Can someone kindly show me where the above script ig going wrong?

Thanks
Ernie

User avatar
jvierra
Posts: 13687
Joined: Tue May 22, 2007 9:57 am
Contact:

Replacing text in a file

Post by jvierra » Wed Sep 12, 2012 12:37 am

This is closer to what you want.

strDirectoryName = "e:test2texttxt" 'Wscript.Arguments(0)
strOldText = "XXXXXXXXXXXXX" 'Wscript.Arguments(1)
strReplaceText = "Life is a box of chocolates" 'Wscript.Arguments(2)

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strDirectoryName)

For each file In objFolder.Files

Set strm=file.OpenAsTextStream()
strText = strm.ReadAll()
strm.Close
strNewText = Replace(strText, strOldText, strReplaceText)
Set strm = file.OpenAsTextStream(2,-2)
strm.Write strNewText
strm.Close

Next

User avatar
EBrant
Posts: 99
Joined: Thu Feb 02, 2012 1:51 am

Replacing text in a file

Post by EBrant » Wed Sep 12, 2012 1:39 am

Thanks very much Jim, :)
Ernie

Locked