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
Replacing text in a file
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.
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.
Replacing text in a file
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
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