I'm a command-line dinosaur. Vim (Vi IMproved) is my favorite text editor. And I write quite a few little batch files.
Here are a few useful tricks that work with cmd.exe on Windows XP.
Sometimes I want to create a file whose name includes the current date and time. By combining the magic %DATE% and %TIME% environment variables, with for /f and a little bit of string substitution, I can create that filename.
%DATE%
%TIME%
for /f
REMREM "Tue 06/14/2005" -> "06/14/2005"REMfor /f "tokens=2" %%i in ("%DATE%") do set MDY=%%iREMREM "06/14/2005" -> "2005-06-14"REMfor /f "delims=/ tokens=1,2,3" %%i in ("%MDY%") do set YMD=%%k-%%i-%%jREM "16:44:39.72" -> "1644"REMfor /f "delims=: tokens=1,2" %%i in ("%TIME%") do set HM=%%i%%jREMREM " 237" -> "0237" (%TIME% < 10:00:00.00 contains a leading space)set HM=%HM: =0% xcopy /yf %1 %YMD%_%HM%.bak
See for /? and set /? to explain everything that the comments don't.
for /?
set /?
Sometimes it's useful to time operations.
@setlocal@if (%_echo%)==() set _echo=off@echo %_echo%call :time T1set T2=%T1%set Iter=0@echo T1 = %T1%:repeatCostlyOperation.execall :time T2set /A DeltaT=%T2% - %T1%set /A Iter=%Iter% + 1set /A Avg=%DeltaT% / %Iter%@echo DeltaT = %DeltaT%, Avg = %Avg%, Iter = %Iter%, T2 = %T2%goto :repeat:timeset TT=%TIME%for /f "delims=: tokens=1" %%i in ("%TT%") do set hrs=%%ifor /f "delims=: tokens=2" %%i in ("%TT%") do set min=1%%ifor /f "delims=: tokens=3" %%i in ("%TT%") do set sec=1%%ifor /f "delims=. tokens=1" %%i in ("%sec%") do set sec=%%iset /A %1=3600 * %hrs% + 60 * (%min%-100) + (%sec%-100)goto :EOF
The :time subroutine calculates the number of seconds that have elapsed today. The business with 100 is to handle the case that min or sec is 08 or 09, which Cmd's expression evaluator considers to be malformed octal.
:time
min
sec
08
09
set /? explains set /A arithmetic. call /? explains subroutine syntax and goto :EOF.
set /A
call /?
goto :EOF
Extending this code so that it works past midnight is left as the proverbial exercise for the reader.
Page rendered at Thursday, November 20, 2008 7:39:19 AM (Pacific Standard Time, UTC-08:00)
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
E-mail