拆分文本字段搜索特定的文本字符串并保存在多个目录中 [英] Split text fiel searching for specific string of text and saving in mutltiple directories

查看:20
本文介绍了拆分文本字段搜索特定的文本字符串并保存在多个目录中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a text file that I need to split according to values in the 4th column of information. The script would need to split the lines of text according the the value of the first character of the text on that column and then split the file and save it to specified folders(different) under the original file name. for instance anything starting with the numbers 1 or 2 would be saved as file, anything starting with the number 4, 5 or 6 as another file and so on. Sample of file below:

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 

推荐答案

我建议使用 Select 语句进行区分,因为我认为这样更容易理解.我用来管理输出文件的字典.

I'd suggest to do the discrimination with a Select statement, because I consider that a lot easier to understand. A dictionary I'd use to manage the output files.

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

这篇关于拆分文本字段搜索特定的文本字符串并保存在多个目录中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆