Wednesday, June 2, 2010

time stamping windows directory and file names

This is something I have blogged about before, but I thought it worth posting again.  Special characters need to be eliminated to create a time stamp that can be used as a Windows file name. The `date` program in Unix has a number of very useful options for this.  Windows cmd shell is more limited. This is what I use:

:: rtime.cmd
@echo off

set realdate=%date:/=.%
set realdate=%realdate:* =%
set realtime=%time::=.%
set realtime=%realtime:* =%
set timestamp=%realdate%.%realtime%
echo %timestamp%

This command script uses 'variable substitution' from the set command to remove special characters (e.g. :  / ) unacceptable as Windows file or directory names . This line:
set timestamp=%realdate%.%realtime%


can be changed as needed for more CSV compatible logging:
set timestamp="%realdate%","%realtime%"


Once cached, it runs pretty fast and is suitable for lightweight logging:

$ time /cygdrive/C/Security/rtime.cmd
06.02.2010.11.04.05.99

real    0m0.202s
user    0m0.015s
sys     0m0.031s

$ time /cygdrive/C/Security/rtime.cmd
06.02.2010.11.04.12.65

real    0m0.062s
user    0m0.000s
sys     0m0.015s

$ time /cygdrive/C/Security/rtime.cmd
06.02.2010.11.04.14.68

real    0m0.062s
user    0m0.000s
sys     0m0.015s

No comments:

Post a Comment