user2243697
user2243697

Reputation: 11

VBS script to batch process multiple files (replacing string of text)

I have more 10000 files in a folder (extension *.WIR - plain text inside though). I want to find and replace specific line inside every single one. My problem is this line is slightly different in every file + I don't know how to force script to batch process.

Example file 1 have: "INSULATION RESIS 20.0 M ohm"

Example file 2 have: "INSULATION RESIS 100.0 M ohm"

Example file 3 have: "INSULATION RESIS 0.2 M ohm" ...

I need to change them all to "INSULATION RESIS 500.0 M ohm".

Is there any chance VBS script can use wildcards to batch process everything in the same time. How can I do that?

Many thanks in advance for any response.

Upvotes: 1

Views: 2946

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200193

I would probably do something like this:

Set fso = CreateObject("Scripting.FileSystemObject")

Set re = New RegExp
re.Pattern = "(INSULATION RESIS) \d+\.\d+ (M ohm)"

For Each f In fso.GetFolder("...").Files
  If LCase(fso.GetExtensionName(f)) = "wir" Then
    filename = f.Path
    tempname = filename & ".tmp"

    Set f_in = fso.OpenTextFile(filename)
    Set f_out = fso.OpenTextFile(tempname, 2)
    Do Until f_in.AtEndOfStream
      f_out.WriteLine re.Replace(f_in.ReadLine, "$1 500.0 $2")
    Loop
    f_in.Close
    f_out.Close

    f.Delete
    fso.MoveFile tempname, filename
  End If
Next

This solution avoids potential memory exhaustion due to large input files by processing each file line-by-line. Disadvantage of this solution is that the output-handling requires additional steps (write output to temporary file, replace input file with temporary file).

Upvotes: 2

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38745

Three strategies for three (sub)problems:

cscript 01.vbs
xxA 1.0 BxxA 1.1 BxxA 123.456 Bxx
xxA 500.0 BxxA 500.0 BxxA 500.0 Bxx
Option Explicit

Dim oFS : Set oFS = CreateObject("Scripting.FileSystemObject")

' use RegExp to replace all occurrences of "A #.# B" in a string
Dim reRpl : Set reRpl = New RegExp
Dim sTest : sTest     = "xxA 1.0 BxxA 1.1 BxxA 123.456 Bxx"
reRpl.Global = True
reRpl.Pattern = "(A )\d+\.\d+( B)"
WScript.Echo sTest
WScript.Echo reRpl.Replace(sTest, "$1500.0$2")

' use FileSystemObject/Stream to read/write from/to file
Dim sAll : sAll = oFS.OpenTextFile(WScript.ScriptFullName).ReadAll()
WScript.Echo sAll
oFS.CreateTextFile(WScript.ScriptFullName, True).Write sAll

' use FileSystemObject/Folder/File to loop directory
Dim oFile
For Each oFile In oFS.GetFolder(".").Files
    WScript.Echo oFile.Name
Next

username24.txt
01.vbs
00.vbs

Upvotes: 2

Related Questions