| 1. |
Solve : I am looking to change filenames sequentially in a given directory? |
|
Answer» I used to know how to do this back in my MS-DOS days (when Windows 3.x was a big thing) but I haven't used batch files since switching to Windows 95 (it's HARD to believe that it's only been 15 years since then; seems a lot longer ago than that! ).
A good copying job, Billrich. Quote from: QBall on December 30, 2010, 10:15:40 PM Microsoft needs to incorporate a batch file-renamer into it's file manager! I wouldn't think that it'd take too much code to add / change the existing file rename utility Windows Explorer has? http://blogs.msdn.com/b/oldnewthing/archive/2010/05/31/10017567.aspx Quote from: QBall on December 30, 2010, 10:07:41 PM Thanks for the help! I'd love to see Billrich's answer to this question. The short answer is that it "enables delayed expansion" which you can look up on Google. Code: [Select]import java.io.*; public class SequentialRename { public static void main (String[] args){ if ( args.length != 1 ){ System.out.println("Usage: java SequentialRename [extension]"); System.exit(1); } String extension = args[0]; String[] directory = (new File(".")).list(); int counter = 1; for( String name : directory ){ if ( name.endsWith( extension) && (new File(name)).isFile() ){ String newName = name.replaceAll( "\\."+extension+"$" , "" ) + counter + "." + extension; System.out.println( "old name: " + name + " , new name: " + newName ); ( new File( name ) ).renameTo ( new File( newName ) ); counter++; } } } } run using Java, Code: [Select]java SequentialRename jpg [recovering disk space - old attachment deleted by admin]would that not also replace files that happen to have only a name part that end with the extension? Such as, in your example, files like testjpg and filejpg and so forth? (probably an easy fix, and it's probably not something that would be encountered frequently) Also- honest question- why did you select the screen name "JavaHater", yet most of the code you've posted here has been exclusively in java? hi, thanks for your comments Quote from: BC_Programmer on December 31, 2010, 01:57:53 AM would that not also replace files that happen to have only a name part that end with the extension? Such as, in your example, files like testjpg and filejpg and so forth? (probably an easy fix, and it's probably not something that would be encountered frequently)No, it will only replace those that are actual files, and those that have a dot "." , as in ".jpg". (the string for the regular expression actually is "\.jpg$" when combined). |
|