VBS:合并具有几乎相同名称的文件

时间:2015-02-14 10:09:28

标签: file vbscript merge text-files


我在文件夹中有数百个文件,名称几乎相同,如 1560q90j-a.txt 1560q90j-b.txt 。这些文件是临时(随机)生成的 如何合并给定文件夹中的文件,这些文件在开头具有相同的九个字符,后跟一个不同的新文件。同时删除源文件:

 Commandline: copy 1560q90j-a.txt+1560q90j-b.txt 1560q90j.txt
 Commandline: del 1560q90j-?.txt
 Commandline: copy atiy09hr-a.txt+atiy09hr-a.txt atiy09hr.txt
 Commandline: del atiy09hr-?.txt

稍后我会将所有新文件合并到一个文件中,其中一行空行作为文件内容之间的分隔符:

 Commandline: copy 560q90j.txt+blankline.txt+atiy09hr.txt+blankline.txt+ ... Allfile.txt

也许有人能够帮助我在VBS中使用脚本来实现我的愿望。

谢谢!米奇

2 个答案:

答案 0 :(得分:0)

这应该这样做:

Const ForReading = 1
Const ForAppending = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")

objStartFolder = "C:\temp\test\" 'the folder where your text files are

Set objFolder = objFSO.GetFolder(objStartFolder)

Set colFiles = objFolder.Files
For Each objFile in colFiles
        Set writefile = objFSO.OpenTextFile("C:\Temp\" & Left(objFile.Name, 8) & ".txt", ForAppending, True)'open output file based on first 8 letters of found file
        set readfile = objFSO.OpenTextFile(objStartFolder & objFile.Name, ForReading, False) 'open found file
        contents = readfile.ReadAll  'read its content
        writefile.WriteLine(contents)  'append to output file
        readfile.close  'close file
        writefile.Close()
        objFSO.DeleteFile(objStartFolder & objFile.Name) 'delete file
Next

答案 1 :(得分:0)

谢谢,它对第一部分很有用。 第二部分我采用这个脚本: Const ForReading = 1 Set objFSO = CreateObject("Scripting.FileSystemObject") Set objOutputFile = objFSO.CreateTextFile("output.txt") ' in CurrenDirectory strComputer = "." ' This Computer Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") Set FileList = objWMIService.ExecQuery _ ("ASSOCIATORS OF {Win32_Directory.Name='C:\Temp'} Where " _ & "ResultClass = CIM_DataFile") For Each objFile In FileList Set objTextFile = objFSO.OpenTextFile(objFile.Name, ForReading) strText = objTextFile.ReadAll objTextFile.Close objOutputFile.WriteLine strText & vbcrlf Next objOutputFile.Close

再次感谢情人节问候