读取子文件夹中的文件

时间:2013-06-03 20:28:15

标签: vbscript text-files subdirectory

我正在尝试创建一个脚本,我们可以从不同子文件夹中的文件列表中输出特定字符串。

我的脚本可以正常工作但只能用于一个目录。我需要一些帮助才能使其适用于子文件夹

Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set folder = objFSO.GetFolder("D:\vbs\logs\") ' here i have loads of subfolders with *.txt 
Set outfile = objFSO.CreateTextFile("D:\vbs\ok\test.txt") ' my output file

for each file in folder.Files
    Set testfile = objFSO.OpenTextFile(file.path, ForReading)

    Do While Not testfile.AtEndOfStream

        If instr (testfile.readline, "central") then ' i output every lines where there is the word "central" 
            outfile.writeline testfile.readline
        End If

        if instr (testfile.readline, "version") then  ' i use this to parse my output file to get a indication between every files read

            num = testfile.readline
            mag = Split(num)
        elseif testfile.AtEndOfStream = true then
            outfile.writeline "Shop " & mag(4)
        end if
    Loop
    testfile.close
next
outfile.close

2 个答案:

答案 0 :(得分:1)

有关文件夹递归示例的详细信息,请参阅this answer

关于现有代码的一个注意事项:ReadLine方法的每次调用都会从文件中读取下一行,如下所示:

If instr (testfile.readline, "central") then
  outfile.writeline testfile.readline
End If

输出包含单词“central”的行(正如您的评论所说),但该行。

如果要输出包含要检查的单词的行,则必须将读取行存储在变量中并继续使用该变量:

line = testfile.ReadLine
If InStr(line, "central") Then
  outfile.WriteLine line
End If

答案 1 :(得分:0)

我会将整个For...Each块封装到一个新的子例程中,然后添加一个新的For...Each块来捕获父文件夹中的所有subFolders。我在您的脚本中添加了该功能,请参阅下文。

Const ForReading = 1
Const Start_Folder = "D:\vbs\logs\" ' here i have loads of subfolders with *.txt 

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set outfile = objFSO.CreateTextFile("D:\vbs\ok\test.txt") ' my output file


'Call the Search subroutine to start the recursive search.
Search objFSO.GetFolder(Start_Folder)

'Close the outfile after all folders have been searched
outfile.Close

Sub Search(sDir)

    for each file in sDir.Files
        Set testfile = objFSO.OpenTextFile(file.path, ForReading)

        Do While Not testfile.AtEndOfStream

            If instr (testfile.readline, "central") then ' i output every lines where there is the word "central" 
                outfile.writeline testfile.readline
            End If

            if instr (testfile.readline, "version") then  ' i use this to parse my output file to get a indication between every files read

                num = testfile.readline
                mag = Split(num)
            elseif testfile.AtEndOfStream = true then
                outfile.writeline "Shop " & mag(4)
            end if
        Loop
        testfile.close
    next

    'Find EACH SUBFOLDER.
    For Each subFolder In sDir.SubFolders

        'Call the Search subroutine to start the recursive search on EACH SUBFOLDER.
        Search objFSO.GetFolder(subFolder.Path)
    Next

End Sub