Click here to Skip to main content
Click here to Skip to main content

Tagged as

Replace parameters with values in text file with VBScript

, 3 May 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
Introduction...

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"

License

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

Share

About the Author

byapparov
Database Developer
United Kingdom United Kingdom
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.1411022.1 | Last Updated 3 May 2010
Article Copyright 2010 by byapparov
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid