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

Vbscript 如果字符串在文件名中匹配,则将多个.TXT文件合并为一个,vbscript,Vbscript,如果我在目录中有一个文件列表,如果文件名中的字符串模式匹配,我想合并这些文件,有人能帮我一个要求吗 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

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

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
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

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

添加文件内容的顺序是否重要?这无关紧要。但是,在合并所有文件@AnsgarWiechersI中的第一行和最后三行时,应忽略所有文件中的第一行和最后三行,我已尝试了提供的代码,但这些文件没有得到响应mergerd@Ansgar Wiechers@anilbusupalli当我测试代码时,它运行得很好。请注意,这不是一个交钥匙解决方案。您需要将其与代码的其余部分集成。还要注意,输出文件是在当前工作目录中创建的。使用完整路径定义
filename
,以获取特定文件夹中的输出。
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