1

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

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

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

e.g. Contents were:

john_list.txt auto.john.doc

After script:

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!"
Woodstock
  • 22,184
  • 15
  • 80
  • 118
  • I will upvote as soon as your comments aren't lying anymore (and - optional - you disclose how you will deal with "johnny"). – Ekkehard.Horner Jun 26 '13 at 14:20
  • What do you mean 'comments aren't lying anymore?' what did I lie about? – Woodstock Jun 27 '13 at 06:24
  • you don't deal with underscores and spaces but with johns and daves. – Ekkehard.Horner Jun 27 '13 at 06:55
  • Haha oh yes indeed, I wasn't posting as my solution , just a solution that I had to cobble together. I thought I might as well post for the next person who needs help, so they might get more help than I did. – Woodstock Jun 27 '13 at 14:57

1 Answers1

3

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")
Community
  • 1
  • 1
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328