O R G A N I C / F E R T I L I Z E R: “mid” like functionality in batch script

Jul 31, 2009

“mid” like functionality in batch script

for awhile, i used for looping to do a lot of manipulation in batch scripts until i ran across this gem.  a friend of mine asked me how to manipulate a date string awhile back.  this is what i came up with.

let’s begin with the date /t command.  running it gives us this output:

Fri 07/31/2009

 

most date formats with respect to dates in filenames generally don’t use “/” or include the short day name “fri”.  my conventional method is to push this through a for loop and break out the thing into tokens.  i’ve done this in below by utilizing “/” and “,” as the delimiters.

for /f "tokens=1,2,3,4 delims=/, " %a in ('date /t') do @echo %b%c%d

 

now we get this output when we echo %b%c%d.

07312009

 

the challenge i got was how to get the date to show up as 090731.  if we tried to use “0” as a delimiter, it would clearly fail as 07 and 09 have zeroes in them.  here’s an example:

for /f "tokens=1-5 delims=/,0 " %a in ('date /t') do @echo 0%e0%b%c

 

we get the output we want but only by forcing 0s into the echo statement.  this can’t be a good idea because eventually the month will increment where there’s no 0 preceding it… like 10, 11, or 12.  that’s when i found this other cool method.

for /f "tokens=1-2 delims= " %a in ('echo %date%') do @set mydate=%b
set mm=%mydate:~0,2%
set dd=%mydate:~3,2%
set yy=%mydate:~8,2%

 

now i can echo back the output as echo %yy%%mm%%dd% and achieve the result we expect.

090731

 

this is what i imagine the syntax to look like:

%[var]:~[1st position],[last position]%

incidentally, it accepts negative numbers as well.  so, you could achieve the same effect using %mydate:~-2%.  this is not the same as %mydate:~0,-2% by the way.

why batch files?  i don’t know.  i guess some people still like them. :)