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

本文介绍了一款使用VBScript编写的脚本工具,该工具可以在指定文件夹内批量替换文本文件中的指定字符串。通过简单的参数配置,用户可以轻松实现文件内容的批量更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值