我有一个名为 data.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
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
...
以下是关于如何将此单个文本文件拆分为多个文本文件的代码:
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 ,这是输出文本文件:
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 。
预期结果应为:
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 :(得分:3)
只需将fileTo.WriteLine(matches(0).SubMatches(0))
添加到if if:
if matches.Count > 0 then
writeTo = saveTo & matches(0).SubMatches(0) & ".txt"
set fileTo = fso.CreateTextFile(writeTo)
fileTo.WriteLine(matches(0).SubMatches(0))
else
fileTo.WriteLine(line)
end if
您的输出将是:[记事本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