VBScript Basics, Part 24 | Replace Lines (Replace Command)

VBScripting (.vbs) Basic tutorial on how to use the replace command on a certain line number, or when everything is the exact same.

Code Example: (Note: change the “«” and “»” back to greater than, and less than signs. In addition, make sure “cd” is set to the actual file you want.)

Option Explicit
Dim fso, cd, cd2, objC, objRd, objwR, linecount, before, current, after, change, i
Const vbRead=1, vbApp=8

Set fso = CreateObject(“Scripting.FileSystemObject”)
cd = Replace(Wscript.ScriptFullName, Wscript.ScriptName, “file2.txt”)
‘Or you could use the location of your file from anywhere so, something like this:

cd2 = Replace(Wscript.ScriptFullName, Wscript.ScriptName, “new.txt”)

fso.CreateTextFile cd2

Set objC = fso.OpenTextFile(cd, vbRead)
Do Until objC.AtEndOfStream
linecount = linecount+1

Set objRd = fso.OpenTextFile(cd, vbRead)
For i = 1 to linecount
If i « 2 Then
before = objRd.ReadLine
Call oText

ElseIf i = 2 Then
current = objRd.ReadLine
Call cText

ElseIf i » 2 Then
after = objRd.ReadAll
Call nText
Exit For
End If

fso.CopyFile cd2, cd, True
fso.DeleteFile cd2

Sub oText
Set objwR = fso.OpenTextFile(cd2, vbApp)
objwR.WriteLine before
End Sub

Sub cText
change = Replace(current, “Travis”, “Adam”)
Set objwR = fso.OpenTextFile(cd2, vbApp)
objwR.WriteLine change
End Sub

Sub nText
Set objwR = fso.OpenTextFile(cd2, vbApp)
objwR.Write after
End Sub

Know the Basics:
Replace(String, FindSubstring, ReplaceSubstring)