我有这个文本文件示例:
W1M0130 03/12/2012 00:00 SS_001 0 0 0 0 0 0 0 0 03/12/2012 00:00 SS_002 15 14 149 64 0 0 0 1 03/12/2012 00:00 SS_003 4 3 233 100 0 0 0 1 03/12/2012 00:00 SS_004 0 0 0 0 0 0 0 0 03/12/2012 00:00 SS_005 0 0 0 0 0 0 0 0 03/12/2012 00:00 SS_006 0 0 0 0 0 0 0 0 03/12/2012 00:00 SS_007 0 0 0 0 0 0 0 0 03/12/2012 00:00 SS_008 0 0 0 0 0 0 0 0 $ END W1M0130 03/12/2012 00:00 SS_001 0 0 0 0 0 0 0 0 03/12/2012 00:00 SS_002 15 14 149 64 0 0 0 1 03/12/2012 00:00 SS_003 4 3 233 100 0 0 0 1 03/12/2012 00:00 SS_004 0 0 0 0 0 0 0 0 03/12/2012 00:00 SS_005 0 0 0 0 0 0 0 0 03/12/2012 00:00 SS_006 0 0 0 0 0 0 0 0 03/12/2012 00:00 SS_007 0 0 0 0 0 0 0 03/12/2012 00:00 SS_008 0 0 0 0 0 0 0 0 $ END W1M0200 03/12/2012 00:30 SS_001 0 0 0 0 0 0 0 0 03/12/2012 00:30 SS_002 12 11 136 58 0 0 0 1 03/12/2012 00:30 SS_003 3 2 213 91 0 0 0 1 03/12/2012 00:30 SS_004 0 0 0 0 0 0 0 0 03/12/2012 00:30 SS_005 0 0 0 0 0 0 0 0 03/12/2012 00:30 SS_006 0 0 0 0 0 0 0 0 03/12/2012 00:30 SS_007 0 0 0 0 0 0 0 0 03/12/2012 00:30 SS_008 0 0 0 0 0 0 0 0 $ END W1M0230 ...
这是我的vbscript代码:
textFile = "C:\data.txt"
saveTo = "C:\"
writeTo = ""
headingPattern = "(W[0-9][A-Z][0-9]*)"
Dim fso, fileFrom, regex
Set fso = CreateObject("Scripting.FileSystemObject")
Set fileFrom = fso.OpenTextFile(textFile)
Set regex = New RegExp
With regex
.Pattern = headingPattern
.IgnoreCase = false
.Global = True
End With
While fileFrom.AtEndOfStream <> True
line = fileFrom.ReadLine
Set matches = regex.Execute(line)
If matches.Count > 0 Then
writeTo = saveTo & matches(0).SubMatches(0) & ".txt"
Set fileTo = fso.CreateTextFile(writeTo)
Else
fileTo.WriteLine(line)
End If
Wend
Set fileFrom = Nothing
Set fso = Nothing
Set regex = Nothing
第一个输出文件的文件名将是W1M0130.txt,内容将是下面的行,直到下一个文件名(W1M0200)。文件名均以W开头,内容行均以日期开头,但最后一行始终为$ END。
仅当文本文件中的模式只有一个(V1M0130然后W1M0200然后W1M0230)时,VBScript代码才能正常工作,但是如果文本文件包含两个或多个该模式,我将很难。(W1M0130然后另一个W1M0130然后W1M0200然后W1M0230)
W1M0130.txt应该类似于:
W1M0130 03/12/2012 00:00 SS_001 0 0 0 0 0 0 0 0 03/12/2012 00:00 SS_002 15 14 149 64 0 0 0 1 03/12/2012 00:00 SS_003 4 3 233 100 0 0 0 1 03/12/2012 00:00 SS_004 0 0 0 0 0 0 0 0 03/12/2012 00:00 SS_005 0 0 0 0 0 0 0 0 03/12/2012 00:00 SS_006 0 0 0 0 0 0 0 0 03/12/2012 00:00 SS_007 0 0 0 0 0 0 0 0 03/12/2012 00:00 SS_008 0 0 0 0 0 0 0 0 $ END W1M0130 03/12/2012 00:00 SS_001 0 0 0 0 0 0 0 0 03/12/2012 00:00 SS_002 15 14 149 64 0 0 0 1 03/12/2012 00:00 SS_003 4 3 233 100 0 0 0 1 03/12/2012 00:00 SS_004 0 0 0 0 0 0 0 0 03/12/2012 00:00 SS_005 0 0 0 0 0 0 0 0 03/12/2012 00:00 SS_006 0 0 0 0 0 0 0 0 2012年3月12日00:00 SS_007 0 0 0 0 0 0 0 0 03/12/2012 00:00 SS_008 0 0 0 0 0 0 0 0 $ END
CreateTextFile
替换现有文件,因此您要替换之前编写的文件。使用OpenTextFile
打开文件进行追加。设置第三个参数以True
创建文件(如果文件不存在)。
Set fileTo = fso.OpenTextFile(writeTo, 8, True)
另外,遇到一行时,请关闭文件$END
:
Else
fileTo.WriteLine(line)
If line = "$END" Then fileTo.Close
End If
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句