Avatar of SwamyN
SwamyN
 asked on

how do I write a batch file to rename files in a folder based on the date

I have a folder with many files having the format 'test-ddMMyyyy.txt'
i need a batch file to rename all the files in this folder to yyyyMMdd-Test.txt
Microsoft DOSWindows Batch

Avatar of undefined
Last Comment
SwamyN

8/22/2022 - Mon
t0t0

Please try

@echo off
setlocal enabledelayedexpansion

for /f "tokens=*" %%a in ('dir /a-d /b *.xxx') do (
   set fn=%%~na
   call :rename "!fn:~-9!" "%%~xa" "%%~dpnxa"
)
exit /b

:rename
   ren "%~3" "!fn:~-4,4!!fn:~-6,2!!fn:~-8,2!-!fn:%~1=!%~2"
exit /b
ASKER CERTIFIED SOLUTION
t0t0

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
SwamyN

ASKER
Hi...this is exactly what i wanted.....I'm a novice at writing bat files, so could you please tell me what  "setlocal enabledelayedexpansion" does, as also the structure of the for loop you used.
and what does ~dpnxa do?
 
 
t0t0

setlocal enabledelayedexpansion is necessary to expand variables for each iteration of the loop otherwise the variable in the loop would just be set to a single value throughout the loop's life. try it with the follwing;

set count=0
for /l %%i in (1,1,10) do (
   set count=%%i
   echo %count%
)

the loop will enumerate count and you'll get only 10's printed to the screen.

using delayedexpansion expands count for each iteration but instead of using %count% we have to use !count! instead as in:

set count=0
for /l %%i in (1,1,10) do (
   set count=%%i
   echo !count!
)

so, to expand variables inside loops we reference them using !...! instaed of %...%.

I had to use CALL to a subroutine because !fn:%~1=! does not work with normal environment variables so this was passed as !fn:~-9!. this was a substitution to 'cancel' out the static part of the filename.

%%a is the value set to by the loop, in this case the filename.

%%~da gives you the drive letter of that file
%%~pa gives you the path of that file
%%~na gives you the filename of that file
%%~xa gives you the extenxion of that file

%%~nxa would give you just the filename and the extension of that file whereas,

%%~dpnxa gives you the full path including the drive, the path, the filename and the extension of that file.

if you look at the help for FOR then it gives you some info on it there. type:

FOR /?

at the command line.

 
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
SwamyN

ASKER
precise and to the point