Search code examples
replacevbscriptscriptingbasicadsutil.vbs

Read the contents in a text file and replace it with specified text in another text file using VBS


I've been trying to create a VBS script to read the contents of text in one text file and replace it with specified text located in another text file.

I'm trying to get the following script to read the contents in a file called first.txt. Once it does that its supposed to replace the specified text in a file called second.txt with the content read from the file called first.txt. This is what i have so far. Its replacing all text in the second.txt file instead of replace the specified text. Any ideas on this before i pull out my last strand of hair.Thanks!

Const ForReading = 1
Const ForWriting = 2
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("first.txt",1)
strFileText = objFileToRead.ReadAll()
objFileToRead.Close

strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "@sec", strFileText)

Set objFile = objFSO.OpenTextFile("second.txt", ForWriting)
objFile.WriteLine strNewText
objFile.Close

Solution

  • Hey @GeertBellekens your right and thank you for bringing this up. I was going to just correct this. This previous script seemed to have only read the second line from the first.txt file so I made minor changes in variable deceleration and reading the text by specified line. Here is the final working script.Its reading the first line of text in the first.txt file and replacing it with the "@sec" text located in the second.txt file. Let me know if it works for you. Thanks!!.

    Here is the working code:

    Option Explicit
    
    
    Dim fso,strFilename,strSearch,strReplace,objFile,oldContent,newContent,strpw,objfso,strText,strNewText,filename,f,i,strline
    
    
    filename = "first.txt"
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set f = fso.OpenTextFile(filename)
    
    For i = 1 to 0
        f.ReadLine
    Next
    
    strLine = f.ReadLine
    Wscript.Echo strLine
    
    f.Close
    
    
    
    
    
    Const ForReading = 1
    Const ForWriting = 2
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.OpenTextFile("second.txt", ForReading)
    
    strText = objFile.ReadAll
    objFile.Close
    strNewText = Replace(strText, "@sec", strLine)
    
    Set objFile = objFSO.OpenTextFile("second.txt", ForWriting)
    objFile.WriteLine strNewText
    objFile.Close