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.
This topic is 11 years and 6 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
User avatar
EBrant
Posts: 99
Last visit: Wed Apr 23, 2014 2:22 am

Replacing text in a file

Post by EBrant »

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
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Replacing text in a file

Post by jvierra »

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
Last visit: Wed Apr 23, 2014 2:22 am

Replacing text in a file

Post by EBrant »

Thanks very much Jim, :)
Ernie
This topic is 11 years and 6 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked