我有一个 output.txt 文件,其中包含以下内容:
Windows 6543765432
Linux 4534653463
MacOS 3564325
Ubuntu 8235646255
我想创建一个 VBScript,它搜索 output.txt 中的所有数值并将它们除以 1024,以便可以将 KB 中的内存更改为 MB。我在这里批量尝试过,但由于 2 GB 的限制,它在上述情况下不起作用。
您的首要任务是修改一个小文件的结构化文本。这种任务的“设计模式”是:
Get a FileSystemObject
Specify the full file path
Read the content
Modify the content
Write the modified content back
您的修改子任务涉及对非常量/变化部分的计算;那么应该使用“RegExp.Replace with Function”策略:
Define a RegExp (global, identify the parts to change)
.Replace(input, GetRef("function to do the computations on the parts"))
在您的情况下,该函数应将(字符串)部分转换为数字,然后除以,然后返回转换为字符串的结果。
在代码中:
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
对于更花哨的输出:
FiMoReFunc = Right(Space(20) & FormatNumber(CDbl(sM) / 1024, 1, True) & " Unit", 20)
输出:
Windows 6,390,395.9 Unit
Linux 4,428,372.5 Unit
MacOS 3,480.8 Unit
Ubuntu 8,042,623.3 Unit
试试这个
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