Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 590
Praveenks Avatar asked May 27 '26 23:05

Praveenks


1 Answers

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.)
like image 58
Zev Spitz Avatar answered May 31 '26 16:05

Zev Spitz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!