Home > VBScript > How to use VBScript to search and replace in a file

How to use VBScript to search and replace in a file


In this example  I have a .WS file used for IBM Client Access that is being imported into Citrix.  We need to change the .KMP pointer in the file to a network location.
 
Create a folder in C: called "Search" and then file in that folder called "TEST.WS" (it can be .txt or anything else Notepad can open) and past the following in it…
 
[Profile]
ID=WS
Description=
Version=9
[Translation]
IBMDefaultView=Y
DefaultView=
IBMDefaultDBCS=Y
DefaultDBCS=
[Communication]
AutoConnect=Y
Link=telnet5250
Session=5250
ForceConfigPanel=N
[Telnet5250]
HostName=testserver.test.com
Security=CA400
SSLClientAuthentication=Y
CertSelection=AUTOSELECT
[5250]
HostCodePage=037-U
PrinterType=IBM3812
[Keyboard]
CuaKeyboard=2
Language=United-States
IBMDefaultKeyboard=N
DefaultKeyboard=C:Documents and SettingsAdministratorApplication DataIBMClient AccessEmulatorprivateAS400.KMP
[LastExitView]
A=3 22 29 648 553 3 8 18 400 0 IBM3270— 37
 
 
The script is below
 
Const ForReading = 1
Const ForWriting = 2
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Pattern = "KMP"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:SearchTest.ws", ForReading)
Do Until objFile.AtEndOfStream
    strSearchString = objFile.Readline
    Set colMatches = objRegEx.Execute(strSearchString) 
 If colMatches.Count > 0 Then
  For Each strMatch in colMatches  
   Wscript.Echo strSearchString
   TexttoChange=strSearchString
 
   ‘This is the new string you want to add:
   NewText="DefaultKeyboard=\TestUNCShareChanged.KMP"
 
   ‘wscript.echo TexttoChange
   ‘wscript.echo NewText
   ‘objFile.Close
   Set objFile = objFSO.OpenTextFile("d:Searchtest.ws", ForReading)
   strText = objFile.ReadAll
   objFile.Close
   
   strNewText = Replace(strText, TexttoChange, NewText)
   
   Set objFile = objFSO.OpenTextFile("C:SearchTest.ws", ForWriting)
   objFile.WriteLine strNewText
   objFile.Close
   wscript.quit
  Next
 END IF
‘wscript.echo strSearchString
Loop
objFile.Close
Advertisements
Categories: VBScript
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: