Click here to Skip to main content
6,634,665 members and growing! (19,349 online)
Email Password   helpLost your password?
General Programming » Algorithms & Recipes » Regular Expressions     Intermediate

Regular Expression Filename Find and Replace

By M Harris

Perform find and replace on file names with regular expressions.
C# 2.0.NET 2.0, Win2K, WinXP, Win2003, VistaVS2005, Dev
Posted:10 Feb 2007
Views:38,999
Bookmarked:51 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
25 votes for this article.
Popularity: 6.68 Rating: 4.78 out of 5

1

2
2 votes, 8.0%
3
4 votes, 16.0%
4
19 votes, 76.0%
5
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


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.
Occupation: Software Developer
Location: Australia Australia

Other popular Algorithms & Recipes articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 21 of 21 (Total in Forum: 21) (Refresh)FirstPrevNext
NewsThere's a new version of the RegEx Tester Tool ! PinmemberBucanerO_Slacker0:33 2 Mar '08  
GeneralGetDirectory using dlgOpen.ShowDialog() Pinmemberavnersimon1:44 20 Jan '08  
GeneralSimilarity with my article PinmemberGast1283:48 21 May '07  
GeneralRe: Similarity with my article Pinmemberpsyphen22:54 23 May '07  
GeneralRe: Similarity with my article PinmemberS Douglas6:19 20 Jul '07  
GeneralRename Master PinmemberLbas21:06 15 Feb '07  
GeneralWell done Mark PinmemberChris Austin9:01 15 Feb '07  
GeneralFeature suggestion: Rename/move to different folder Pinmembermikellekim9:18 14 Feb '07  
GeneralRe: Feature suggestion: Rename/move to different folder PinmemberM Harris12:19 14 Feb '07  
GeneralSee also RenameIt on SourceForge Pinmembermikellekim9:15 14 Feb '07  
GeneralRe: See also RenameIt on SourceForge PinmemberM Harris12:22 14 Feb '07  
General32 bit version PinmemberDaniel Kamisnki9:41 12 Feb '07  
GeneralRe: 32 bit version PinmemberM Harris12:22 12 Feb '07  
GeneralRe: 32 bit version PinmemberDaniel Kamisnki13:46 12 Feb '07  
GeneralRe: 32 bit version PinmemberM Harris13:52 12 Feb '07  
GeneralWell done. PinmemberPalewhale.14:10 11 Feb '07  
GeneralErr..but why? Pinmembersharpiesharpie9:44 10 Feb '07  
AnswerRe: Err..but why? PinmemberM Harris15:07 10 Feb '07  
GeneralRe: Err..but why? Pinmembersharpiesharpie5:15 11 Feb '07  
GeneralRe: Err..but why? PinmemberM Harris12:59 11 Feb '07  
GeneralRe: Err..but why? PinmemberDerek Read14:37 12 Feb '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 10 Feb 2007
Editor: Deeksha Shenoy
Copyright 2007 by M Harris
Everything else Copyright © CodeProject, 1999-2009
Web19 | Advertise on the Code Project