Praveenks
Praveenks

Reputation: 1496

Replace multiple text in a text file using vbscript

I am trying to replace 3 text from a text file.I tried this-

Const ForReading = 1
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("W:\Test.txt", ForReading)

strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "Aron_", "Lori_")
strNewText1 = Replace(strText, "Aron", "Jason")   'Not working
strNewText2 = Replace(strText, "Sketa", "Skicia") 'Not working


Set objFile = objFSO.OpenTextFile("W:\Test.txt", ForWriting)
objFile.WriteLine strNewText 
objFile.WriteLine strNewText1 'Not working
objFile.WriteLine strNewText2 'Not working


objFile.Close

i am not able to figure out how to do multiple replacement.The code working perfect for single replace function but not more than one...plz help

Upvotes: 2

Views: 41315

Answers (1)

Zev Spitz
Zev Spitz

Reputation: 15297

You need to call Replace on the results of the previous Replace:

Const ForReading = 1
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("W:\Test.txt", ForReading)

strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "Aron_", "Lori_")
strNewText1 = Replace(strNewText, "Aron", "Jason")
strNewText2 = Replace(strNewText1, "Sketa", "Skicia")

Set objFile = objFSO.OpenTextFile("W:\Test.txt", ForWriting)
objFile.WriteLine strNewText2 

objFile.Close


You could actually reuse a single variable, instead of having strNewText, strNewText1, strNewText2.

strText = Replace(strText, "Aron_", "Lori_")
strText = Replace(strText, "Aron", "Jason")
strText = Replace(strText, "Sketa", "Skicia")

and later:

objFile.WriteLine strText


Also, you might want to consider using regular expressions for matching multiple values at a time. (Search on SO for VBScript regular expressions or VBA regular expressions.)

Upvotes: 10

Related Questions