cmd line rename file with date and time

user611620 picture user611620 · Feb 13, 2011 · Viewed 204.7k times · Source

Project moving forwards, I can see why creating .bat files to do things can become addictive! I can now save somefile.txt at regular intervals, I then rename somefile.txt by adding the time and date to create a unique file name

ren somefile.txt somefile_%time:~0,2%%time:~3,2%-%date:~-10,2%%date:~3,2%%date:~-4,4%.txt

As an example, the code above has just renamed somefile.txt to somefile_1317_13022011.txt (1317hrs on 13th February 2011)

I ran

ren somefile.txt somefile_%time:~0,2%%time:~3,2%-%date:~-10,2%%date:~7,2%%date:~-4,4%.txt 

yesterday, it ran successfully until midnight, and then it crashed (syntax error) although it was saving as 12012011 for the date (12th Jan 2011) instead of the correct date of 12022011.

Will the current version ran past midnight? Am I confusing myself with UK vs US date format?

Answer

silentpete picture silentpete · Jul 17, 2012

Animuson gives a decent way to do it, but no help on understanding it. I kept looking and came across a forum thread with this commands:

Echo Off
IF Not EXIST n:\dbfs\doekasp.txt GOTO DoNothing

copy n:\dbfs\doekasp.txt n:\history\doekasp.txt

Rem rename command is done twice (2) to allow for 1 or 2 digit hour,
Rem If before 10am (1digit) hour Rename starting at location (0) for (2) chars,
Rem will error out, as location (0) will have a space
Rem and space is invalid character for file name,
Rem so second remame will be used.
Rem
Rem if equal 10am or later (2 digit hour) then first remame will work and second will not
Rem as doekasp.txt will not be found (remamed)


ren n:\history\doekasp.txt doekasp-%date:~4,2%-%date:~7,2%-%date:~10,4%_@_%time:~0,2%h%time:~3,2%m%time:~6,2%s%.txt
ren n:\history\doekasp.txt doekasp-%date:~4,2%-%date:~7,2%-%date:~10,4%_@_%time:~1,1%h%time:~3,2%m%time:~6,2%s%.txt

I always name year first YYYYMMDD, but wanted to add time. Here you will see that he has given a reason why 0,2 will not work and 1,1 will, because (space) is an invalid character. This opened my eyes to the issue. Also, by default you're in 24hr mode.

I ended up with:

ren Logs.txt Logs-%date:~10,4%%date:~7,2%%date:~4,2%_%time:~0,2%%time:~3,2%.txt
ren Logs.txt Logs-%date:~10,4%%date:~7,2%%date:~4,2%_%time:~1,1%%time:~3,2%.txt

Output:

Logs-20121707_1019