Monday, February 23, 2009

DOS: Renaming files with today’s date

Was asked by someone if there was an easy way to rename a file with today’s date and here is one way to do that:

Copy the following command into a batch file and save it as dateRenamer.bat

for /f "tokens=1-4 delims=/ " %%d in ("%date%") do rename %1 %%g%%e%%f_%1

And you call it so: dateRenamer test.txt
And it will rename the file test.txt to 20090223_test.txt.

Notes:

To see what the for command is doing, check out: http://www.computerhope.com/forhlp.htm, and the gist is:

Split the date into 4 tokens, (starting with token name d and ending with g) using the delimiters “/” and space. %date% date formatted like: mon 02/23/2009 and hence d becomes the day, e the month, f the day and g the year. These variables are then used to create the new file name.

The one thing you will notice is that the date is pre-pended to the original file name. I did this because I could not come up with an easy way to break down the name of the file-path into filename and extension. By pre-pending the date to the file name, I avoid the issues of having to split the file name.

No comments: