VBScript 根据需要从文件内容设置的变量将文本文件拆分为多个文件

VBScript to split a text file into multiple files based on a variables that needs to be set from file contents

我希望有人能够帮助我,基本上我有一个文本文件,我需要根据将包含在文件中的变量进行拆分......

我在下面添加了源文件的外观示例……

我需要做的是忽略页眉和页脚,然后根据第二个分隔符将文件拆分为单独的文件,因此对于第一行,这将是“1001”,文件应将所有匹配的引用分组到文件中,然后应用页眉和页脚。

页眉应该是一个变量(在这个例子中它应该是第一个分隔符),页脚应该是记录数,然后文件需要用一个变量名保存(见下文)

源文件示例:

Header is Here|1
Testcust1|1001|thisis 1
Testcust1|1001|thisis 2
Testcust1|1001|thisis 3
Testcust1|1001|thisis 4
Testcust2|1002|thisis 1
Testcust2|1002|thisis 2
Testcust3|1003|thisis 3
Testcust4|1004|thisis 1
Testcust4|1004|thisis 2
Testcust4|1004|thisis 3
Testcust1|1001|thisis 5
Testcust1|1001|thisis 6
Testcust1|1001|thisis 7
Testcust1|1001|thisis 8
Testcust1|1001|thisis 9
Footer|15

下面是我希望第一个输出文件看起来像基于源:

Testcust1|1
Testcust1|1001|thisis 1
Testcust1|1001|thisis 2
Testcust1|1001|thisis 3
Testcust1|1001|thisis 4
Testcust1|1001|thisis 5
Testcust1|1001|thisis 6
Testcust1|1001|thisis 7
Testcust1|1001|thisis 8
Testcust1|1001|thisis 9
Footer|9

这需要保存为“C:\Testcust1(Datetime).txt”

不胜感激!

理论:

"Grouping" 在 VBScript 中表示 "Dictionary"。因此,使用字典将要写入的文件存储在分组所基于的键下 - 如应用 here and here.

一步一步:

 Dim sLine : sLine = tsIn.ReadLine()
 Read a line like 'Footer|15' or 'Testcust4|1004|thisis 1'
 Dim aLine : aLine = Split(sLine, "|")
 Split it into an array
 If 2 = UBound(aLine) Then
    it's a data line like 'Testcust4|1004|thisis 1'
    If Not dicF.Exists(aLine(1)) Then
       We haven't seen the key, e.g. '1004'
       Dim sFSpec : sFSpec = oFS.BuildPath("..\data", aLine(1) & ".txt")
       build file spec for this key
       Set dicF(aLine(1)) = oFS.CreateTextFile(sFSpec)
       create the file and store it in dicF
       dicF(aLine(1)).WriteLine aLine(0) & "|1"
       write the header
    End If
    dicF(aLine(1)).WriteLine sLine
    write the data line to this key's file
 End If

练习:

  Dim oFS  : Set oFS  = CreateObject("Scripting.FileSystemObject")
  Dim dicF : Set dicF = CreateObject("Scripting.Dictionary")
  Dim tsIn : Set tsIn = oFS.OpenTextFile("..\data691670.txt")
  Do Until tsIn.AtEndOfStream
     Dim sLine : sLine = tsIn.ReadLine()
     Dim aLine : aLine = Split(sLine, "|")
     If 2 = UBound(aLine) Then
        If Not dicF.Exists(aLine(1)) Then
           Dim sFSpec : sFSpec = oFS.BuildPath("..\data", aLine(1) & ".txt")
           Set dicF(aLine(1)) = oFS.CreateTextFile(sFSpec)
           dicF(aLine(1)).WriteLine aLine(0) & "|1"
        End If
        dicF(aLine(1)).WriteLine sLine
     End If
  Loop
  tsIn.Close
  Dim tsOut
  For Each tsOut in dicF.Items()
      tsOut.WriteLine "Footer|" & tsOut.Line - 2
      tsOut.Close
  Next

1001.txt

的输出
Testcust1|1
Testcust1|1001|thisis 1
Testcust1|1001|thisis 2
Testcust1|1001|thisis 3
Testcust1|1001|thisis 4
Testcust1|1001|thisis 5
Testcust1|1001|thisis 6
Testcust1|1001|thisis 7
Testcust1|1001|thisis 8
Testcust1|1001|thisis 9
Footer|9