vba 使用特定字符串重命名文件夹中的文件 vbs

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17317916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 21:52:50  来源:igfitidea点击:

rename a file in a folder with a specific string vbs

filevbavbscriptrename

提问by Woodstock

Can some one please help explain how I can write some vbs script that searches for files with a particular string and renames them?

有人可以帮助解释我如何编写一些 vbs 脚本来搜索具有特定字符串的文件并重命名它们吗?

For example, say I have a folder c:\test

例如,假设我有一个文件夹 c:\test

I want to search in c:\test for every file with the word John and replace with say the word Dave...

我想在 c:\test 中搜索每个带有 John 一词的文件,并用 Dave 这个词替换...

e.g. Contents were:

例如内容是:

john_list.txt auto.john.doc

john_list.txt auto.john.doc

After script:

脚本后:

dave_list.txt auto.dave.doc

dave_list.txt auto.dave.doc

Can you help?

你能帮我吗?

Thanks!

谢谢!

SOLUTION:

解决方案:

Dim sName
Dim fso
Dim fol

' create the filesystem object
Set fso = WScript.CreateObject("Scripting.FileSystemObject")

' get current folder
Set fol = fso.GetFolder("c:\TEST")

' go thru each files in the folder
For Each fil In fol.Files
' check if the file name contains underscore
If InStr(1, fil.Name, "john") <> 0 Then
    ' replace underscore with space
    sName = Replace(fil.Name, "john", "dave")
    ' rename the file
    fil.Name = sName
End If
Next

' echo the job is completed
WScript.Echo "Completed!"

回答by Ansgar Wiechers

For recursing into subfolders you need something like this. Replacing text in the name of the file can be done like this:

对于递归到子文件夹,你需要像这样。可以像这样替换文件名中的文本:

f.Name = Replace(f.Name, "john", "dave")