Speedy Full Directory File Name Find and Replace In Windows 7
Today I’m going to show you a handy script I came up with when I needed to do a bulk find & replace rename all of the files I had in a folder. This has only been tested on Windows 7 so I’m unable to say if it will work on versions lower or higher than that.
So with that said, here is the script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Set fsfo = CreateObject("Scripting.FileSystemObject") Set dir = fsfo.GetFolder("D:\images") num = 0 For Each file In dir.files nfile = file.Name nfile = Replace(nfile,"_th","_thumb") if (nfile<>file.Name) then file.Move(file.ParentFolder+"\"+nfile) num = num + 1 end if Next num = CStr(num) MsgBox "Renamed " + num + " files" |
I use this for renaming a lot of images, hence the ‘_th’ to ‘_thumb’ replacement in the code.
I am no expert in VB, I wrote this just as a quick and dirty script to serve my own purpose, but I’ll have a go at explaining what everything does as I wanted to share it in case it will help someone else.
The first line creates a FSO or a File System Object. This allows us to do various things involving the file system, but most importantly it let’s us loop through existing files & rename them. The second line uses that FSO to open (get) the folder that contains the files we want to change the filenames of. The third line sets a counter so we can output how many files were renamed later.
The next block loops through all the files using a For Each
. Just like in any other language this goes through each item in an array, or in this case each file found in our folder. We then store the file name. Then we find and replace. The replace function is simple to use Replace(input, find, replacement)
if you weren’t sure. We then check that against the current file name, if it isn’t the same we move the file to the same location, but with it’s new filename. You could replace this with copy if you wanted to create copies instead. We also add one to our counter variable. Then we tell the For Each
to move onto the next item.
Finally we convert our counters value to a string (CStr
) then output it in a message box so we know how many files were renamed for us. Why the conversion? Well apparently VBScript cannot output integers in strings like other languages you may be familiar with such as PHP, it will throw an error instead.
As I mentioned. This was a very quick script I put together with next to no knowledge of VBScript. Why? Well I needed to rename 10,000 images, but didn’t want to install a program just for that purpose. I’m either lazy or resourceful, I’ll let you decide which.