如果文件名中的字符串匹配,则将多个 .TXT 文件合并为一个

Combining multiple .TXT files into one if a string matches in filename

有人可以帮我解决我在目录中有文件列表的要求吗?如果文件名中的字符串模式匹配,我想合并这些文件?

AAAL_555A_ORANGE1_F190404.TXT
AAAL_555A_ORANGE2_F190404.TXT
AAAL_555A_ORANGE3_F190404.TXT
AAAL_555A_ORANGE4_F190404.TXT
AAAL_555A_MANGO_F190404.TXT
AAAL_555A_MANGO2_F190404.TXT
AAAL_555B_APPLE_F190404.TXT
AAAL_555B_ORANGE_F190404.TXT
AAAL_555B_Orange_F190404.TXT

如果 filename='555A' 的第二部分和第三部分由 ORANGE 组成,那么所有 Oranges 内容文件将合并为一个文件,文件名为 AAAl_555A_ORANGE.txt.

如果 filename='555B' 的第二部分和第三部分由 ORANGE 组成,那么所有 Oranges 内容文件将合并为一个文件,文件名为 AAAl_555B_ORANGE.txt.

如果 filename='555A' 的第二部分和第三部分由 MANGO 组成,则所有 Oranges 内容文件将合并为一个文件,文件名为 AAAl_555A_MANGO.txt,依此类推

Set ObjFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "C:\test"
Set objfolder = ObjFSO.GetFolder(objStartFolder)
Set colfiles = objfolder.Files
'intFile = FreeFile()
For Each objFile In colfiles
    temparr1 = Split(objFile.Name, "_")
    MsgBox temparr1(2)
    If (InStr(1, temparr1(1), "555A") > 0 Or InStr(1, temparr1(1), "555A")) > 0 And (InStr(1, temparr1(2), "ORANGE ") > 0 Or InStr(1, temparr1(2), "ORANGE ")) Then
        'Here the logic am trying to figure out
        'Merge all orange files into "AAAL_ORANGE _555A.txt"
    ElseIf InStr(1, temparr1(1), "555A") > 0 Or InStr(1, temparr1(1), "555A") > 0 Or InStr(1, temparr1(2), "MANGO") > 0 Or InStr(1, temparr1(2), "MANGO") Then
        'Here the logic am trying to figure out
        'Merge all orange files into  "AAAL_MANGO_555A.txt"
    End If
Next

FileSystemObject.OpenTextFile() 方法的参数允许您指定您想要 a) 创建文件以防它不存在,以及 b) 将新内容追加到文件末尾。

在您的特定情况下,可能看起来有点像这样:

Set re = New RegExp
re.Pattern = "\d+$"

For Each objFile In colfiles
    a = Split(objFile.Name, "_")

    'Construct the basename of the output file from the elements of the split
    'input filename. Use a regular expression replacement to remove trailing
    'digits from the third element.
    basename = a(0) & "_" & a(1) & "_" & re.Replace(a(2), "")
    filename = basename & ".txt"

    If Left(objFile.Name, Len(basename)) = basename Then
        Set outFile = ObjFSO.OpenTextFile(filename, 8, True)
        Set inFile  = ObjFSO.OpenTextFile(objFile.Path)
        Do Until inFile.AtEndOfStream
            outFile.WriteLine inFile.ReadLine
        Loop
        inFile.Close
        outFile.Close
    End If
Next

要省略输入文件开头或结尾的行,请参阅 类似问题。