Skip to content

Instantly share code, notes, and snippets.

@hiscaler
Created July 12, 2012 03:28
Show Gist options
  • Save hiscaler/3095493 to your computer and use it in GitHub Desktop.
Save hiscaler/3095493 to your computer and use it in GitHub Desktop.
VBScript Replace file contents
Dim filePath, fileContents, dFileContents
filePath = "C:\"
' 查找所有 .lst 扩展名文件
Dim fs, f, array1, f1
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFolder("C:\")
Set fc = f.Files
For Each f1 in fc
If (Right(f1.name, 4) = ".lst") Then
processingFile filePath & f1.name
End If
Next
Function processingFile(ByVal fileName)
Dim fileContents, dFileContents, find, replaceWith
find = ","
replaceWith = vbCrLf
fileContents = getFile(fileName)
' 用“替换内容”替换文件中所有“查找内容”
dFileContents = replace(fileContents, find, replaceWith, 1, -1, 1)
' 比较源文件和替换后的文件
if dFileContents <> fileContents Then
' 保存替换后的文件
writeFile fileName, dFileContents
If False Then
Wscript.Echo "Replace done."
If Len(replaceWith) <> Len(find) Then
' 计算替换总数
Wscript.Echo ((Len(dFileContents) - Len(fileContents)) / (Len(replaceWith)-Len(find))) & " replacements."
End If
End If
Else
' Wscript.Echo "Searched string Not In the source file"
End If
End Function
' 读取文件
Function getFile(ByVal fileName)
If fileName <> "" Then
Dim fs, fileStream
Set fs = CreateObject("Scripting.FileSystemObject")
on error resume Next
Set fileStream = fs.OpenTextFile(fileName)
getFile = fileStream.ReadAll
End If
End Function
' 写文件
Function writeFile(ByVal fileName, ByVal Contents)
Dim outStream, fs
on error resume Next
Set fs = CreateObject("Scripting.FileSystemObject")
Set outStream = fs.OpenTextFile(fileName, 2, True)
outStream.Write Contents
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment