質問

I have an output.txt file which has following content:

Windows        6543765432
Linux          4534653463
MacOS          3564325
Ubuntu         8235646255

I want to create a VBScript which searches for all numeric values in output.txt and divide them by 1024 so that memory in KB can be changed into MB. I have tried in batch here, but due to 2 GB limitation it's not working in above case.

役に立ちましたか?

解決

Your top-level task is to modify a small file of structured text. The 'design pattern' for such a task is:

Get a FileSystemObject
Specify the full file path
Read the content
Modify the content
Write the modified content back

Your sub-task of modification involves computations on non-constant /varying parts; then a 'RegExp.Replace with Function' strategy should be used:

Define a RegExp (global, identify the parts to change)
.Replace(input, GetRef("function to do the computations on the parts"))

In your case, that function should convert the (string) parts to numbers, divide then, and return the result converted to strings.

In code:

  Option Explicit
  Const FSPEC = "..\testdata\txt\19556079.txt"
  Dim oFS : Set oFS  = CreateObject( "Scripting.FileSystemObject" )
  Dim sAll : sAll = Modify(oFS.OpenTextFile(FSPEC).ReadAll())
  oFS.CreateTextFile(FSPEC).Write sAll
  WScript.Echo oFS.OpenTextFile(FSPEC).ReadAll()

Function Modify(s)
  Dim re : Set re = New RegExp
  re.Global = True
  re.Pattern = "\d+"
  Modify = re.Replace(s, GetRef("FiMoReFunc"))
End Function

Function FiMoReFunc(sM, sP, sS)
  FiMoReFunc = CStr(CDbl(sM) / 1024)
End Function

For a more fancy output:

FiMoReFunc = Right(Space(20) & FormatNumber(CDbl(sM) / 1024, 1, True) & " Unit", 20)

output:

Windows            6,390,395.9 Unit
Linux              4,428,372.5 Unit
MacOS                  3,480.8 Unit
Ubuntu             8,042,623.3 Unit

他のヒント

Try this

Option Explicit

Const FILE = "output.txt"
Dim fso
Dim ts,line
Dim match,matches
Dim os,mem

Set fso = CreateObject("Scripting.FilesystemObject")
Set ts = fso.OpenTextFile(FILE)

With New RegExp
  .IgnoreCase = True
  While Not ts.AtEndOfStream
    line = ts.ReadLine

    .Pattern = "[a-z]+"
    Set matches = .Execute(line)
    For Each match In matches
      os = match.Value
    Next

    .Pattern = "\d+"
    Set matches = .Execute(line)
    For Each match In matches
      mem = (CDbl(match.Value) / 1024)
    Next

    WScript.Echo os & vbTab & mem
  Wend
End With

Set ts = Nothing
Set fso = Nothing
WScript.Quit
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top