user3801383
user3801383

Reputation: 13

vbscript replace text - not in all document

Morning, i have a ini file that i modify with this vbscript:

Dim FileName, Find, ReplaceWith, FileContents, dFileContents
Find         = WScript.Arguments(0)
ReplaceWith  = WScript.Arguments(2)
FileName     = WScript.Arguments(1)

FileContents = GetFile(FileName)
dFileContents = replace(FileContents, Find, ReplaceWith, 1, -1, 1)
WriteFile FileName, dFileContents

function GetFile(FileName)
  If FileName<>"" Then
    Dim FS, FileStream
    Set FS = CreateObject("Scripting.FileSystemObject")
      on error resume Next
      Set FileStream = FS.OpenTextFile(FileName)
      GetFile = FileStream.ReadAll
  End If
End Function

function WriteFile(FileName, Contents)
  Dim OutStream, FS
  on error resume Next
  Set FS = CreateObject("Scripting.FileSystemObject")
    Set OutStream = FS.OpenTextFile(FileName, 2, True)
    OutStream.Write Contents
End Function

now i call cscript replace.vbs "what i want to search" "name of file" "what i want to replace"

This work but this script replace all the word in "what i want to search". In my "name of file" there are more entry with the same name and i want to sobstitute only the first. Waht can i do? thanks

Upvotes: 1

Views: 238

Answers (1)

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38745

To cite Ansgar: When in doubt, read the Docs. Pay attention to the count parameter. This will solve your specific problem - replacing only the first occurrence.

A better, more general approach: Use a RegExp that identifies the value to change by specifying its key.

Upvotes: 1

Related Questions