0

如何使用 vbscript 在某个文件夹中存在的多个文本文件中查找和替换特定字符串?

4

2 回答 2

3
' This code replaces one string by another inside files looping though subfolders.
' It is vbscript so copy the text below in a .txt file and rename to .vbs
' It will take any non zero bytes file except for extensions you filter out in advance.

Option Explicit
Dim objFilesystem, objFolder, objFiles, objFile, tFile, objShell, objLogFile,objFSO, objStartFolder, colFiles
Dim SubFolder, FileText, bolWriteLog, strLogName, strLogPath, strCount, strCount2, strOldText, strNewText, strEXT
bolWriteLog = True
Const ForReading = 1
Const ForWriting = 2
Const TriStateUseDefault = -2
Set objFilesystem = WScript.CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("wscript.Shell")
strLogName = "log.txt"
strLogPath = "C:\" & strLogName

strCount = 0
strCount2 = 0
strOldText="Dim"
strNewText="Dim-"
strEXT = "exe,dll,ps"

'Initialize log file
If bolWriteLog Then
   on error resume next
   Set objLogFile = objFileSystem.OpenTextFile(strLogPath, 2, True)
   WriteLog "############### Start Log ##################"
   If not err.number = 0 then
      msgbox "There was a problem opening the log file for writing." & chr(10) & _
         "Please check whether """ & strLogPath & """ is a valid file and can be openend for writing." & _
         chr(10) & chr(10) & "If you're not sure what to do, please contact your support person.",vbCritical, "Script Error"
      wscript.quit
   end if
   on error goto 0
end If


Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "C:\temp\"

Set objFolder = objFSO.GetFolder(objStartFolder)
Wscript.Echo objFolder.Path
Set colFiles = objFolder.Files
For Each objFile in colFiles
    Wscript.Echo objFile.Name
' Now we have an exception for all files that can not be opened in text modus: all extensions such as "exe" should be listed upfront.
    If Instr(1,strEXT, Right(LCase(objFile.Name), 3))=0 and objFile.size> 0 Then
ReplaceText(objFile)
End If

Next

ShowSubfolders objFSO.GetFolder(objStartFolder)



Sub  ReplaceText(objFile)

    strCount = strCount + 1
        WriteLog("Opening " & objFile.Name)
        Set tFile = objFile.OpenAsTextStream(ForReading, TriStateUseDefault)
        FileText = tFile.ReadAll
        tFile.Close
        If InStr(FileText, strOldText) Then
             WriteLog("Replacing " & strOldText & " with " & strNewText & ".")
             FileText = Replace(FileText, strOldText, strNewText)
                WriteLog("Text replaced")
        Else
                WriteLog(strOldText & " was not found in the file.")
                strCount2 = strCount2 +1
        End If
        Set tFile = objFile.OpenAsTextStream(ForWriting, TriStateUseDefault)
        tFile.Write FileText
        tFile.Close
        FileText = ""
strCount = 0
strCount2 = 0
End Sub



Sub ShowSubFolders(Folder)
For Each Subfolder in Folder.SubFolders
    Wscript.Echo Subfolder.Path
    Set objFolder = objFSO.GetFolder(Subfolder.Path)
    Set colFiles = objFolder.Files
    For Each objFile in colFiles
Wscript.Echo objFile.Name
ReplaceText(objFile)
    Next
    ShowSubFolders Subfolder
Next
End Sub


WriteLog "###############  EndLog  ##################"

WScript.Echo "Script Complete"
objShell.Run "C:\" & strLogName

'Clear environment and exit
On Error Resume Next

Set tFile = Nothing
Set objFile = Nothing
Set objFiles = Nothing
Set objFolder = Nothing
Set objLogFile = Nothing
Set objFilesystem = Nothing
Set objShell = Nothing

WScript.Quit

'Subs and functions ********** DO NOT EDIT ***************

sub WriteLog(sEntry)
   If bolWriteLog then objLogFile.WriteLine(Now() & ": Log:      " & sEntry)
End Sub
于 2012-12-07T18:08:34.450 回答
-1

lnafziger,谷歌一些东西,先自己尝试一些东西,如果你卡住了,然后问一个问题,这里有一些功能可以帮助你入门

Function ReplaceTest(patrn, replStr)
  Dim regEx, str1               ' Create variables.
  str1 = "The quick brown fox jumped over the lazy dog."
  Set regEx = New RegExp            ' Create regular expression.
  regEx.Pattern = patrn            ' Set pattern.
  regEx.IgnoreCase = True            ' Make case insensitive.
  ReplaceTest = regEx.Replace(str1, replStr)   ' Make replacement.
End Function

MsgBox(ReplaceTest("fox", "cat"))      ' Replace 'fox' with 'cat'.

在这里可以循环浏览文件

Set fso = CreateObject("Scripting.FileSystemObject")
Call getFilesAndReplace(fso.GetFolder(map))
'--- ---'
Sub getFilesAndReplace(Folder)
  Dim files, file, Subfolder
  on error resume next
  For Each Subfolder in Folder.SubFolders
    Wscript.Echo "check " & Subfolder.path
    For Each file in Subfolder.files
      Wscript.Echo "replacing " & file.path
      'your replace routine
    Next
    Call getFilesAndReplace(Subfolder) 'recurse
  Next
End Sub
于 2012-05-23T10:35:39.407 回答