Click here to Skip to main content
16,019,514 members
Articles / Programming Languages / Javascript
Article

Rename all files in a folder

Rate me:
Please Sign up or sign in to vote.
4.56/5 (10 votes)
30 Apr 20072 min read 83.8K   1.1K   18   11
Replace a string in the names of all the files in a certain folder

Introduction

If you've ever had a directory full of files, all containing a certain string, and you wanted to replace/remove it, this is the script for you.

Background

My CD ripping software always leaves a folder full of files with the following name format CDName_Track_#_SongName.mp3. Since the folder name already carries the name of the CD and I know that every song is a track - I'd like to get rid of the prefix. It takes a minute for a CD with 5 tracks, 3 minutes for an average CD (15 tracks), and more if you rip several CDs... I decided to solve this creatively: a script that iterates through all files in a folder and replaces a string with another. Took 5 minutes to write - so I guess I'm ahead.

Using the code

Just copy the following code into a text file, rename it to have a ".js" extension (or just download the attached file) and set the following 3 parameters:

JavaScript
//////////////////////////////////////////
sFolderName = "D:\\Temp\\Mp3";
sStringToFind = "_Track_";
sStringToReplace = "";
//////////////////////////////////////////

Make sure you include double-\ in the folder name (C-type strings, in .NET I would have used a @).

If you just want to get rid of a string, make the third parameter an empty string.

Save the change file and double-click. In any Windows OS (beginning with Window 98 SE), the Windows Scripting Host (WSH), would execute the file.

Here's the entire code, it's pretty self explanatory:

JavaScript
var sFolderName, sStringToFind;
var nResult;

//////////////////////////////////////////
sFolderName = "D:\\Temp\\Mp3";
sStringToFind = "_Track_";
sStringToReplace = "";
//////////////////////////////////////////

nResult = renameFiles(sFolderName, sStringToFind, sStringToReplace);
WScript.Echo(nResult + " files renamed");

//    Function Name:    renameFiles
//    Parameters:
//    sFolder:    Folder Name
//    sString1:    String to search for
//    sString2:    String to replace
//    Returns:    Number of files renamed
function renameFiles(sFolder, sString1, sString2)
{
    var oFSO, oFile, oFolder;
    var re, index;
    var sName;
    var i = 0, n;

    oFSO = new ActiveXObject("Scripting.FileSystemObject");
    oFolder = oFSO.GetFolder(sFolder);
    try
    {

        index = new Enumerator(oFolder.Files);

        for (; !index.atEnd(); index.moveNext())
        {
            oFile = index.item();
            sName = oFile.Name;
            n = sName.indexOf(sString1);
            if(n != -1)
            {
                try
                {
                    sName = sName.substring(0, n) + sString2 + 
                            sName.substr(n + sString1.length);
                    oFile.Name = sName;
                    i++;
                }
                catch(e)
                {
                    WScript.Echo("Can not rename file " + sName + 
                            " because\n" + e.description);
                }
            }
        }
    }
    catch(e)
    {
        WScript.Echo("Could not access folder " + sFolder + 
                        " because\n" + e.description);
        return 0;
    }
    finally
    {
        oFSO = null;
        re = null;
        return i;
    }
}

Points of Interest

One warning: Antivirus software hates script files. McAfee warns about them as if they were the plague. Norton goes one step further and alters the registry so .js and .vbs files cannot be run. Be aware of it and rest assured - this is not a virus!

History

Things I may end up adding (if anyone is interested):

  • Regular expression, instead of a set string.
  • Recursing through a folder tree.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Product Manager
United States United States
Currently, I manage the West Coast Professional Services team for a large company. Part of my job includes implementing solutions and developing "glue" applications.

I love RAD (Rapid Application Development) - specify a problem, come up with the solution, code it - and change later. This is where coding comes closest to art. Just let it flow...

If you want more biographical items, look at my LinkedIn profile at http://www.linkedin.com/in/gvider and if you'd like to see my opinion on other tech-related subjects, read my blog at http://www.guyvider.com.

Comments and Discussions

 
QuestionRename file Pin
Member 1325624812-Jun-17 22:03
Member 1325624812-Jun-17 22:03 
GeneralRename even subfolders Pin
Samson Fernandes26-Jul-12 21:12
Samson Fernandes26-Jul-12 21:12 
GeneralRe: Rename even subfolders Pin
MaxHacker8-Sep-12 5:29
MaxHacker8-Sep-12 5:29 
QuestionChange a specified file Pin
TwoFace'Z14-Jun-12 23:58
TwoFace'Z14-Jun-12 23:58 
GeneralCopy a server file into client pc Pin
jorgefos15-Apr-08 6:51
jorgefos15-Apr-08 6:51 
GeneralRe: Copy a server file into client pc Pin
Guy Vider15-Apr-08 7:06
Guy Vider15-Apr-08 7:06 
GeneralRe: Copy a server file into client pc Pin
jorgefos16-Mar-11 6:16
jorgefos16-Mar-11 6:16 
QuestionRegular Expression Pin
huntercg17-Oct-07 1:37
huntercg17-Oct-07 1:37 
AnswerRe: Regular Expression Pin
Guy Vider17-Oct-07 6:01
Guy Vider17-Oct-07 6:01 
GeneralsFolderName or sFolder Pin
prophetboy17-May-07 2:04
prophetboy17-May-07 2:04 
GeneralRe: sFolderName or sFolder Pin
Guy Vider17-May-07 5:42
Guy Vider17-May-07 5:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.