Find and Replace

This will find all occurences of a string in a text file and replace it with another string. Multiple strings can be searched and replaced at the same time.

CodeFunctionName
What is this?

Public

Tested

Original Work
': Save the code as a .vbs file.
': findreplace2.vbs mylog.txt "Football,
' Baseball" "Rugby,Golf", 0
' Note : The number of elements in Sear
' ch string must match the number of eleme
' nts in replace string.
' : The search & replace strings are comma delimited.
'
'This code is copyrighted and has ' limited warranties.Please see http://w
' ww.Planet-Source-Code.com/xq/ASP/txtCode
' Id.6835/lngWId.4/qx/vb/scripts/ShowCode.
' htm 'for details. '**************************************

Option Explicit
Dim fso
Dim folder
Dim logfile
Dim newfile
Dim deletefile
Dim finalcontents
Dim objArgs
Dim filename
Dim searchstr
Dim replacestr
Dim CompareMethod
Dim Counter
Set objArgs = WScript.Arguments
Set fso = CreateObject("Scripting.FileSystemObject")
if objArgs.count >= 3 and objArgs.count <=4 Then
filename = objArgs(0)
searchstr = split(objArgs(1),",")
replacestr = split(objArgs(2),",")
if objArgs.count = 4 Then
CompareMethod = objArgs(3)
if CompareMethod < > 0 and CompareMethod < > 1 Then
Wscript.Echo "CompareMethod can only be 0 or 1"
Wscript.Quit(1) 'To indicate error.
End if
Else
CompareMethod = 0 ' Default To vbBinaryCompare.
End if
Else
wscript.echo "Usage: FindReplace.vbs [arguments..]" + vbcrlf + vbcrlf + "Arguments:" + vbcrlf + "File To be Searched" + vbcrlf + "Searched string" + vbcrlf + "String to replace" + vbcrlf + "[Comparison Method]"
wscript.Quit (1) 'To indicate error.
End if
' Check the length of search string and
' replace string.
' Both should be equal otherwise error o
' ut
if Ubound(searchstr) < > Ubound(replacestr) Then
wscript.echo "Search String does Not have corresponding replace string"
wscript.Quit(1)
End if
TextSearch(Filename)

function TextSearch(Filename)
Set logfile = fso.OpenTextFile(filename)
if Err.Number < > 0 Then
Wscript.echo Err.Description
Wscript.Quit (Err.Number)
End if
Counter = 0
finalcontents = logfile.readall
Do While Counter <= Ubound(searchstr)
if CompareMethod = 0 Then
finalcontents = Replace(finalcontents, trim(searchstr(counter)), trim(replacestr(counter)), 1, -1, vbBinaryCompare)
Else
finalcontents = Replace(finalcontents, trim(searchstr(counter)), trim(replacestr(counter)), 1, -1, vbTextCompare)
End if
Counter = counter + 1
Loop
logfile.Close
Set deletefile = fso.getFile(filename)
deletefile.delete
Set newfile = fso.CreateTextFile(filename, true)
newfile.write FinalContents
newfile.close
if Err.Number < > 0 Then
Wscript.echo Err.Description
Wscript.Quit (Err.Number)
End if
Set logfile = nothing
Set deletefile = nothing
Set newfile = nothing
End function

[Filename] [String to search] [String to replace] [Comparison Method (optional)][

Views 4,652

Downloads 1,741

CodeID
DB ID

JeffSmith
26
Revisions

v1.0

Sunday
April
15
2018