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!


1 Answers1

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

DavidPostill
  • 162,382