VB脚本使用文件夹结构替换文本

时间:2012-11-19 11:39:42

标签: vbscript

我是VB Script的新手。我需要VB脚本来替换特定的文本

以下是我的档案目录

  1. E:\ TEST \ 98 \ 6549871 \ 1959893 \ HTML
  2. E:\ TEST \ 98 \ 6549871 \ 1959793 \ HTML
  3. E:\ TEST \ 98 \ 6549876 \ 1959863 \ HTML
  4. E:\ TEST \ 96 \ 6749473 \ 6959895 \ HTML
  5. E:\ TEST \ 99 \ 2548878 \ 5959893 \ HTML
  6. 等,

    每个HTML子文件夹中的test.html和img.html页面都包含。在那个html页面中,我想找到文本 =“img / ,需要替换为 =”/ image / 98/6549871 / 1959893 / HTML / img / 其中 =“/ image / 对所有文件都是通用的,其余值按照文件夹结构(即第1级文件夹名称,第2级文件夹名称,第3级文件夹名称和第4级文件夹名称)

    对于我需要做的每个单独的文件,并且花费太多时间来完成此活动。

    任何机构都可以帮我解决此问题,以便在文件夹目录的单个镜头中替换所有 =“img /

    提前致谢

1 个答案:

答案 0 :(得分:0)

像这样......没有经过测试,但是你会指出正确的方向

Option Explicit

Dim fileCount

Sub ProcessSubDirectory( ByVal directory)

On Error Resume Next

Dim fso
Dim dir
Dim folder
Dim file

Set fso = CreateObject("Scripting.FileSystemObject")
Set dir = fso.GetFolder(directory)

If Err.Number <> 0 THen
    MsgBox "Failed to open dir ( " & directory & " )"
    Exit Sub
End If

On Error Goto 0

For Each file in dir.Files
    Call HandleFileFix( file.Path )
Next

For Each folder in dir.SubFolders
    Call ProcessSubDirectory( folder.Path )
Next

Set fso = Nothing

End Sub

Sub HandleFileFix( ByVal file)

Dim fso
Dim f
Dim fo
Dim contents
DIm path

Set fso = CreateObject("Scripting.FileSystemObject")
Set fo = fso.GetFile( file )
Set f = fso.OpenTextFile( file, 1 )

    path = fo.Path
    path = Replace( path, fo.Drive, "")
    path = Replace( path, fo.Name, "")
    path = Replace( path, "\", "/")

If f.AtEndOfStream = false then
    contents = f.ReadAll
End If

f.Close
Set f = Nothing

contents = Replace( contents, "='img/", "='" & path & "/img/")

' write file back to disk
Set f = fso.OpenTextFile( file, 2 )
f.Write contents
f.Close 
fileCount = fileCount + 1
Set f = Nothing

End Sub

fileCount = 0

Call ProcessSubDirectory( "D:\TEST\" )

MsgBox "done (" & CStr(fileCount) & ")"