2

I have a folder with picture files. Filename structure is ddmmyy2222.png where dd=day, mm=month and yy=year. I'm trying to rename them according to the structure yyyymmdd.png like this:

120516222.png => 20160512.png

010616222.png => 20160601.png

190316222.png => 20160316.png

%'s and " 's are driving me crazy. My last attempt is :

FOR /F %%n IN ('dir /b ') DO (

set "oldfile=%%n"

set "d=%oldfile:~0,2%"

set "m=%oldfile:~2,2%"

set "y=%oldfile:~4,2%"

set "newfile=20%y%%m%%d%"

echo.%newfile%

)

But I could not even reach RENAME statement as I did not get what I need in ECHO. What's wrong? Many thanks!


  • There are apps out there that will batch rename files for you. Doing this with cmd sounds like a world of hurt. Might be time to learn some powershell scripting if the apps won't work for you. – jcollum Jun 2 '16 at 20:14
  • Or why not just skip the MS'isms and try Python instead; there are plenty of examples that will help you get where you wish. Even as a novice you will be running past this level. – Hannu Jun 2 '16 at 20:16
  • Also take a look at this superuser.com/questions/347931/… -- not a dupe exactly but relevant – jcollum Jun 2 '16 at 20:18
0

What's wrong

You need to enabledelayedexpansion.

  • Delayed Expansion will cause variables to be expanded at execution time rather than at parse time.

Use the following batch file (test.cmd):

@echo off
setlocal EnableDelayedExpansion
for /f %%n in ('dir /b *.png') do (
  set "oldfile=%%n"
  set "d=!oldfile:~0,2!"
  set "m=!oldfile:~2,2!"
  set "y=!oldfile:~4,2!"
  set "newfile=20!y!!m!!d!"
  echo.!newfile!
  )
endlocal

Notes:

  • Modify the dir command as appropriate.
  • %variable% is replace by !variable! when using Delayed Expansion.

Example:

F:\test>dir *.png
 Volume in drive F is Expansion
 Volume Serial Number is 3656-BB63

 Directory of F:\test

02/06/2016  21:23                 0 010616222.png
02/06/2016  21:23                 0 120516222.png
02/06/2016  21:23                 0 90316222.png
               3 File(s)              0 bytes
               0 Dir(s)  1,769,583,063,040 bytes free

F:\test>test
20160601
20160512
20623190

F:\test>

Further Reading

  • Thanks! It worked. You save me a lot of time and what's more important, I learnt about enabledelaedexpansion. Thanks for the references. – user2261983 Jun 3 '16 at 7:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.