我有这个文本文件样本:
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 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。
如果文本文件中的模式只有一个( W1M0130 然后 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 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
答案 0 :(得分:0)
CreateTextFile
替换现有文件,因此您将替换之前编写的内容。使用OpenTextFile
打开要附加的文件。将第三个参数设置为True
以创建不存在的文件。
Set fileTo = fso.OpenTextFile(writeTo, 8, True)
此外,遇到第$END
行时关闭文件:
Else
fileTo.WriteLine(line)
If line = "$END" Then fileTo.Close
End If
附注:将对象设置为Nothing
为pointless most of the time,所以除非有原因,否则不要这样做。