Link to home
Create AccountLog in
Avatar of tvae
tvae

asked on

Rename a file with datestamp using bat file

This code works like a charm but how can i modify it to not include the day to the file.

for /F "tokens=*" %%G in ('dir "%folder%\*.txt" /B') do ren "%folder%\%%G" "%%~nG %date:/=% %time::=_%%%~xG"

this populates filename Thu 04042013 15_32_40.32.txt and i would like it to show filename 04042013 15_32_40.32.txt
Avatar of Steven Carnahan
Steven Carnahan
Flag of United States of America image

Test this:

set d=%date:~-4,4%%date:~-7,2%%date:~-10,2%

set d=%d: =_%

set t=%time:~0,2%_%time:~3,2%_%time:~6,2%.%time:~9,2%

set t=%t: =0%



for /F "tokens=*" %%G in ('dir "%folder%\*.txt" /B') do ren "%folder%\%%G" "%%~nG %d%_%t%%%~xG"

Open in new window

Avatar of tvae
tvae

ASKER

it populated the time only and no date. this is the filename that got populated
 test850.txt =_16_08_21.61.txt
ASKER CERTIFIED SOLUTION
Avatar of Steven Carnahan
Steven Carnahan
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
This is one of the problems of using the %date% variable.  I would recommend using various other ways, the ones I use I have written down here together with ways to get the different date formats:

https://www.experts-exchange.com/OS/Microsoft_Operating_Systems/MS_DOS/A_1153-Using-dates-in-batch-files-scripts.html

e.g. this is the yyyy-mm-dd-hh-mm-ss.cmd script on that page:

@echo off
echo wscript.echo year(date) ^& "-" ^& right(100+month(date),2) ^& "-" ^& right(100+day(date),2)^& "@" ^& right(100+hour(time),2) ^& "-" ^& right(100+minute(time),2) > "%temp%\dateparts.vbs"
for /f "tokens=1 delims=" %%a in ('cscript //nologo "%temp%\dateparts.vbs"') do set yyyymmddhhmm=%%a

for /F "tokens=*" %%G in ('dir "%folder%\*.txt" /B') do ren "%folder%\%%G" "%%~nG %yyyymmddhhmm%~xG"

Open in new window


Now this is yyyy-mm-dd-hh-mm-ss format but you can adjust, e.g. looks like you want:

ddmmyyyy hh_mm_ss so could use:

@echo off
echo wscript.echo right(100+day(date),2) ^& right(100+month(date),2) ^& year(date)^& " " ^& right(100+hour(time),2) ^& "_" ^& right(100+minute(time),2) ^& "_" ^& right(100+int(second(time)),2)> "%temp%\dateparts.vbs"
for /f "tokens=1 delims=" %%a in ('cscript //nologo "%temp%\dateparts.vbs"') do set mydate=%%a

for /F "tokens=*" %%G in ('dir "%folder%\*.txt" /B') do ren "%folder%\%%G" "%%~nG %mydate%~xG"

Open in new window


Steve