Click here to Skip to main content

Replace parameters with values in text file with VBScript

Introduction...
Sign Up to vote bad good
Add a reason or comment to your vote: x
Votes of 3 or less require a comment
See more: VBScript

Introduction

Here is a VBScript code that replaces values in the original text file and saves results in the destination text file.
 
This code can be helpful for creating parametrized scripts/schemes/input for applications that don't accept parameters in the command line.
 

Code

' Replace.vbs
'--------------------------------------------------
'	Sub Main
'--------------------------------------------------
Dim FileName, FileName2, Find, ReplaceWith, FileContents, dFileContents
Find         = WScript.Arguments(0)
ReplaceWith  = WScript.Arguments(1)
FileName     = WScript.Arguments(2)
FileName2    = WScript.Arguments(3)
 
FileContents = GetFile(FileName)
 
dFileContents = Replace(FileContents, Find, ReplaceWith, 1, -1, 1)
 
if dFileContents <> FileContents Then
  WriteFile FileName2, dFileContents
Else
  Wscript.Echo "Searched string Not In the source file"
End If
'--------------------------------------------------
'	Function GetFile
'--------------------------------------------------
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
'--------------------------------------------------
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
 

Using the Script

cscript Replace.vbs [CurrentDate] 20100208 "GenericScript.txt" "CurrentScript.txt"
 
If you want to replace several parameters, you will need to call this script more than once, but having the source file name same as destination file name:
 
cscript Replace.vbs [CurrentCampaign] DFD435SF "CurrentScript.txt" "CurrentScript.txt"
Posted 9 Feb '10
Edited 3 May '10


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Your Filters
Interested
Ignored
     
  1. SAKryukov (895)
  2. CRDave1988 (264)
  1. SAKryukov (10,992)
  2. Christian Graus (7,218)
  3. OriginalGriff (5,439)
  4. Abhinav S (4,615)
  5. thatraja (4,526)

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
-- There are no messages in this forum --

Advertise | Privacy | Mobile
Web04 | 2.5.120210.1 | Last Updated 3 May 2010
Copyright © CodeProject, 1999-2012
All Rights Reserved. Terms of Use
Layout: fixed | fluid