VBS script realizes the code of traversing batch replacing multi-directory and multi-file content

Time:2019-3-7

Sometimes we need to replace a directory in batches with multiple HTM web pages in subdirectories. Here’s what we want to share.

Copy the following code into a text document, and modify the suffix of the text document to. vbs, and run it directly.

Set WshShell = CreateObject("Wscript.Shell")
WshShell.Run "cmd /c dir /s/b *.htm > list.htm",vbHide
Wscript.Sleep 1000

sFile = "list.htm"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set oFile = objFSO.OpenTextFile(sFile,1)
Do While Not oFile.AtEndOfStream
  strLine = oFile.ReadLine
  If Len(strLine) > 0 Then
   Set File = objFSO.OpenTextFile(strLine, 1)
   aryLines = File.ReadAll
   File.Close
   AryLines = Replace
   Set File = objFSO.OpenTextFile(strLine, 2)
   File.Write aryLines
   File.Close
  End If
Loop
oFile.Close

objFSO.DeleteFile sFile
Set objFSO = Nothing

Cmd/c dir/s/b*.htm > list.htm is to list the HTM files in the subdirectory and save them in the list.htm file.

File replacement is a batch replacement through FileSystem Object in vbs. You can refer to this article for details.

If the substitution contains escaped characters, you need to pay attention to escaping.

PS: Relevant escape characters of VBScript:

“/” (backslash)
VbCrLf
VbTab (horizontal tab)
Chr(8) (backspace)
VbCr (carriage return)
“‘” (single quotation mark)
/ “- >” (double quotation marks)