拆分文本文件,搜索特定的文本字符串并保存在多个目录中

时间:2012-09-03 23:47:11

标签: vbscript

我有一个文本文件,我需要根据第4列信息中的值进行拆分。脚本需要根据该列上文本的第一个字符的值拆分文本行,然后拆分文件并将其保存到原始文件名下的指定文件夹(不同)。例如,以数字1或2开头的任何内容都将保存为文件,任何以数字4,5或6开头的内容都将另存为文件,依此类推。以下文件样本:

0118844 10722     HAWKESBURY VALLEY MOTOR     624G05B    55567191             ROLLER TENSION
0118844 10722     HAWKESBURY VALLEY MOTOR     624G03A    92190654             LOCKING NUT   
0118844 10722     HAWKESBURY VALLEY MOTOR     517A03A    92056367             RADIATOR CAP V6
0118844 10722     HAWKESBURY VALLEY MOTOR     416H04B    92044669             BONNET LOCK
0118844           HAWKESBURY VALLEY MOTOR     213F04D    8972138700           BOLT
0118844           HAWKESBURY VALLEY MOTOR     101B15A    8973628940           THERMOSTAT 

2 个答案:

答案 0 :(得分:0)

使用字典存储识别数字(键)和相应的(打开)文件(值)。循环输入文件的行;对于每一行:剪切数字,将该行写入'数字文件'。不要忘记关闭所有文件。

在代码中:

  Const csDir = "..\data\splits"
  Const csInN = "splits.txt"
  Const csInF = "..\data\splits.txt" ' should be: Const csInF = goFS.BuildPath(csDir, csInN)
  Const cnPos = 47
  Dim aSplits   : aSplits       = Array("12", "456")
  Dim dicSplits : Set dicSplits = CreateObject("Scripting.Dictionary")

  If goFS.FolderExists(csDir) Then goFS.DeleteFolder csDir
  goFS.CreateFolder csDir
  Dim nSplit
  For nSplit = 0 To UBound(aSplits)
      Dim sDir : sDir = aSplits(nSplit)
      Dim nPos
      For nPos = 1 To Len(sDir)
          dicSplits(Mid(sDir, nPos, 1)) = nSplit
      Next
      sDir = goFS.BuildPath(csDir, sDir)
      goFS.CreateFolder sDir
      Set aSplits(nSplit) = goFS.CreateTextFile(goFS.BuildPath(sDir, csInN))
  Next

  Dim tsIn : Set tsIn = goFS.OpenTextFile(csInF)
  Do Until tsIn.AtEndOfStream
      Dim sLine : sLine = tsIn.ReadLine()
      Dim sKey  : sKey  = Mid(sLine, cnPos, 1)
      If dicSplits.Exists(sKey) Then
         aSplits(dicSplits(sKey)).WriteLine sLine
      End If
  Loop
  tsIn.Close

  For nSplit = 0 To UBound(aSplits)
      aSplits(nSplit).Close
  Next

答案 1 :(得分:0)

我建议用Select声明进行歧视,因为我认为这更容易理解。我用来管理输出文件的字典。

Const ForReading     = 1
Const ForWriting     = 2
Const keyPos         = 47
Const inputFileName  = "input.txt"
Const outputFileName = "input.txt"

outputFolders = Array("foo", "bar")

Sub WriteOutput(data, fldr)
  If Not fso.FolderExists(fldr) Then fso.CreateFolder(fldr)
  If Not outputFiles.Exists(fldr) Then outputFiles.Add fldr, fso.OpenTextFile(fso.BuildPath(fldr, outputFileName), ForWriting, True)
  outputFiles(fldr).WriteLine data
End Sub

Set fso = CreateObject("Scripting.FileSystemObject")
Set outputFiles = CreateObject("Scripting.Dictionary")

Set inputFile = fso.OpenTextFile(inputFileName, ForReading, True)
Do Until inputFile.AtEndOfStream
  line = inputFile.ReadLine
  Select Case Mid(line, keyPos, 1)
  Case 1, 2:
    WriteOutput line, outputFolders(0)
  Case 4, 5, 6:
    WriteOutput line, outputFolders(1)
  End Select
Loop
inputFile.Close

For Each f In outputFiles.Items
  f.Close
Next