Click here to Skip to main content
Click here to Skip to main content

Regular Expression Filename Find and Replace

By , 10 Feb 2007
 
Sample image

Introduction

The purpose of this application is to allow you to find and replace files names using regular expressions. At first you may find this would be a pretty strange thing to do. Consider you have a directory full of files that follow two different naming conventions – both contain the same information but just display it differently. If you want to standardize these file names, you would have to edit each filename separately. Renaming several thousand files is not my idea of fun, so I wrote this program to find and replace across file names.

Using the Program

Once you open the program, you can select the directory to find and replace in. Underneath this is the option to find in subdirectories as well.

The find and replace sections allow you to enter a regular expression which you want to find and replace. Standard regular expression syntax applies here. If you are looking for a tool in which to test or design regular expressions, I highly recommend Expresso here on Code Project.

In the Find box you also get a set of options for the Regular Expression, if nothing else I recommend that you keep Compiled turned on as it does make quite a difference to the speed.

Before running the regular expression over your file names, I suggest that you run the test first. This will do everything the replace will except the file rename. Using this allows you to see the results and make sure it is working correctly. A file rename cannot be undone by this program; I'd hate to be responsible for changing 2000 file names into meaningless garbage!

Testing the regular expression.
Testing the regular expression

Under the file menu you will find the ability to save and load "projects". This just saves the values of all the text and check box fields on the form to xml which you can upload at a later date. The idea is that it saves you having to remember or re-write a very complex regular expression in the future.

How it Works

The code for this program is incredibly simple, there is nothing terribly complex at all about it. All actual processing of file names is done in frmReplace. The ReplaceFiles method does all the work, it gets the list of files and then iterates over each of them checking for a Regex match. If there is a match it writes it to the list control as a new item, and then renames the file.

foreach (string file in files)
{
    // move the progress bar along
    pbReplace.Value = ++i;

    // find just the file name.. no need to replace anything in the path
    string name = Path.GetFileName(file);

    // does it match the expression?
    if (rex.IsMatch(name))
    {
        // find out the new name after replacement
        string newName = rex.Replace(name, replace);

        // the path that this came from
        string path = Path.GetDirectoryName(file);

        // add an item to the list showing the replacement
        lstReplacements.Items.Add(
            path + Path.DirectorySeparatorChar + name + " -> " + 
            path + Path.DirectorySeparatorChar + newName);

        // don't rename the file if this is only a test run
        if (!testOnly)
        {
            // rename the file
            File.Move(path + Path.DirectorySeparatorChar + name, 
                path + Path.DirectorySeparatorChar + newName);
        }
    }
}

Conclusion

This has been a very short article, there isn't really much more that can be covered on a program that only has 60 or so lines of code that does anything exciting! I hope you find the program useful.

History

  • 10th February 2007: First public version.

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

About the Author

M Harris
Software Developer
Australia Australia
Member
Mark spends his spare time working on his radio control planes, helicopters and trucks. He devises new ways to make them crash faster and easier than ever before. Mark has progressed this joy of destroying nice toys into build UAV's - which can crash themselves with, or without user input.
 
Mark enjoys all aspects of C#, specifically windows programming and regular expressions.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
NewsThere's a new version of the RegEx Tester Tool !memberBucanerO_Slacker1 Mar '08 - 23:33 
I have released a new version of the RegEx Tester tool. You can download it free from http://www.codeproject.com/KB/string/regextester.aspx and http://sourceforge.net/projects/regextester
 
With RegEx Tester you can fully develop and test your regular expression against a target text. It's UI is designed to aid you in the RegEx developing. It uses and supports ALL of the features available in the .NET RegEx Class.
GeneralGetDirectory using dlgOpen.ShowDialog()memberavnersimon20 Jan '08 - 0:44 
Please correct the function to...
from .... txtDirectory.Text = Path.GetDirectoryName(dlgOpen.FileName);
to
txtDirectory.Text = Path.GetDirectoryName(dlgOpen.FileName.ToString());
 
so it will function ok
=======================
if (dlgOpen.ShowDialog() == DialogResult.OK)
{
txtDirectory.Text = Path.GetDirectoryName(dlgOpen.FileName.ToString());
}
 
Laugh | :laugh:
GeneralSimilarity with my articlememberGast12821 May '07 - 2:48 
I already made in the past an article about file renaming which did not get much attention (see 'File rename using boost regex and boost file system'). That article was also about the use of Boost libraries like Boost.FileSystem and Boost.Regex.
 
Obviously your article uses c# and a 'sharper' GUI.
 
Wkr
me
GeneralRe: Similarity with my articlememberpsyphen23 May '07 - 21:54 
i like pancakes
 

GeneralRe: Similarity with my articlememberS Douglas20 Jul '07 - 5:19 
psyphen wrote:
i like pancakes

 
Without maple syrup? Dead | X|
Roll eyes | :rolleyes:
 

With respect, I must disagree. A quick look at middle management in just about any corporation shows that the dodo not only survived, it's reproducing in record numbers. Christopher Duncan


GeneralRename MastermemberLbas15 Feb '07 - 20:06 
Hi,
Good learning article on using reg-ex, but do you know Rename Master (http://www.joejoesoft.com/rm.php) ? This is a really powerful file rename tool I often use.
 
Thanks for you article,
Lbas

GeneralWell done MarkmemberChris Austin15 Feb '07 - 8:01 
I just have to say it Smile | :)
 
I had recently written a similar app myself for a client who was scared of command lines. It seems that we took a similar approach; good to see that I am not as crazy as friend had told me when I said that I'd be using REs.
 
Cheers
 
My Blog
 

A human being should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts, build a wall, set a bone, comfort the dying, take orders, give orders, cooperate, act alone, solve equations, analyze a new problem, pitch manure, program a computer, cook a tasty meal, fight efficiently, die gallantly. Specialization is for insects.
- -Lazarus Long

GeneralFeature suggestion: Rename/move to different foldermembermikellekim14 Feb '07 - 8:18 
One of the things you might want to do when you're renaming those episodes is to change the folder structure in which they're stored. Correct me if I'm wrong, but it seems that's not currently supported.
GeneralRe: Feature suggestion: Rename/move to different foldermemberM Harris14 Feb '07 - 11:19 
No its not i'm afraid, this is just for file names alone. Eventually i may update this to allow you to insert .net code in the replace window to do the replacement how you choose, it wouldnt be hard.
 
--
Real programmers don't comment their code. It was hard to write, it should be hard to understand.

GeneralSee also RenameIt on SourceForgemembermikellekim14 Feb '07 - 8:15 
RenameIt has a slightly different interface, but has the same basic idea as well as a couple non-regex renaming features. The SourceForge project hasn't seen much activity in recent years, but the tool has been around in various versions and places since 1998.

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 10 Feb 2007
Article Copyright 2007 by M Harris
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid