批量正则替换文件内容(vbscript)

来源:互联网 发布:免费永久个人域名注册 编辑:程序博客网 时间:2024/04/30 06:29

用法:类似于我空间的另一篇--批量正则改文件名
注意:要替换内容的文本型文件都放到同一个文件夹里,第二个参数可以写正则表达式

Dim fso,fd,fl,f,fdpath,findstr,repstr
On Error Resume Next
If WScript.Arguments.Length>=1 Then
 fdpath = WScript.Arguments(0)
Else
 fdpath = InputBox("请输入文件夹路径:","第一个参数")
 If fdpath = "" Then WScript.Quit
End If

If WScript.Arguments.Length>=2 Then
 findstr = WScript.Arguments(1)
Else
 findstr = InputBox("请输入查找字符串:","第二个参数")
 if findstr = "" then WScript.Quit
End If

If WScript.Arguments.Length>=3 Then
 repstr = WScript.Arguments(2)
Else
 repstr = InputBox("请输入替换字符串:","第三个参数")
 If isEmpty(repstr) Then WScript.Quit
 '上面这种判断,解决了用户没输入,得知其按的是确定还是取消
End If

Set fso = CreateObject("scripting.filesystemobject")
Set fd = fso.GetFolder(fdpath)
Set fl=fd.Files
For each f in fl
 doreplace f.Path,findstr,repstr
Next
MsgBox "替换结束,请查看结果。",,"提示"

'读取文件-->替换内容-->保存文件
Function doreplace(filepath,findstr,replacestr)
 Dim FileName, Find, ReplaceWith, FileContents, dFileContents, regEx
 Set regEx=New RegExp
 regEx.Pattern = findstr
 regEx.IgnoreCase = True
 regEx.Global = True
 ReplaceWith =replacestr
 FileName = filepath 
 FileContents = GetFile(FileName)
 dFileContents = regEx.replace(FileContents,ReplaceWith)
 if dFileContents <> FileContents Then
  WriteFile FileName, dFileContents
 End If
End Function
'读取文件 
Function GetFile(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(FileName, 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

原创粉丝点击