Reputation: 1
Here's my situation. I have a few hundred folders (under Windows XP), each of which contain several .jpgs. The names of the folders all got messed up when I accidentally selected all of the folders in the process of renaming one of them.
What I'm setting out to do is write a DOS Batch script which will iterate through each folder, determine the modification date of the newest file within the directory & rename the folder to that date in YYYY-MM-DD format. Hence:
Directory of C:\Work_Area\Messed_up_dir_name
07/11/2012 10:01 AM <DIR>
07/11/2012 10:01 AM <DIR>
03/10/2008 11:00 AM 176,640 image1.jpg
08/07/2007 02:27 PM 25,088 image2.jpg
04/12/2007 04:52 PM 132,608 image3.jpg
02/06/2007 06:11 PM 61,086 image4.jpg
Becomes "C:\Work_Area\2008-03-10\"
This is what I have written so far...
@echo off
REM ITERATE THROUGH EACH DIRECTORY
FOR /F "DELIMS==" %%d in ('DIR "%ROOT%" /AD /B') DO (
ECHO %%d
cd %%d
REM DETERMINE NEWEST FILE
FOR /F %%a in ('DIR /O:-D /B') DO @ECHO %%~ta
cd ..
REM echo Newest=%Newest%
REM move "%%f" "%Newest%"
pause
)
Obviously, the slashes in the date would need to be changed to another character in order for this to be successful. If anyone could help me out with this, it would be much appreciated!
Upvotes: 0
Views: 1710
Reputation: 130819
This script will rename the folders of a directory tree whose root is specified in the 1st argument to the script (%1). I've written the script to satisfy the requirements specified in the 2nd comment to the question.
The script as written will actually echo the rename commands that would run. Simply remove the ECHO command from in front of REN when ready to rename for real.
At least one rename will fail if sibling folders have most recent modified files with the same time stamp.
Also the script cannot rename a folder that does not contain any files.
@echo off
setlocal disableDelayedExpansion
if "%~1" neq "" pushd %1
for /f "eol=: delims=" %%D in ('dir /s /b /ad ^| sort /r') do call :renameFolder "%%D"
exit /b
:renameFolder
pushd %1
for /f "eol=: delims=" %%F in ('dir /b /a-d /o-d') do (
for /f "tokens=1-4* delims=/: " %%A in ("%%~tF") do (
popd
echo ren %1 "%%C-%%A-%%B %%D.%%E"
exit /b
)
)
Upvotes: 3