1

I have a batch file that will format the date as YYYYMMDD and store it as a variable. However, when I want to generate a text output file with the date in the filename, it strips everything after the date. Can someone please help? You will notice in my example that you will get an output file with the text, but the filename will be the date and the .txt extension is stripped off.

@echo off
SETLOCAL ENABLEEXTENSIONS
if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (
  for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
    set '%%a'=%%i
    set '%%b'=%%j
    set '%%c'=%%k))
if %'yy'% LSS 100 set 'yy'=20%'yy'%
set Today=%'yy'%-%'mm'%-%'dd'% 
ENDLOCAL & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%

set mydate=%V_Year%%V_Month%%V_Day% 
echo text for output file > %mydate%.txt
  • Insert `echo --%mydate%--` after setting it, to check it's output. There are better ways ways to get the date/time - independent of locale settings. [Example](http://stackoverflow.com/a/18024049/2152082) – Stephan Jan 12 '16 at 17:58
  • Thanks, Ken. However, all you did was provide me another way of formatting the date. While that is cool, and much simpler, my issue is with the output file. When I try to use the date variable in the filename, it strips off the .txt extension. – SlothLovesChunk Jan 12 '16 at 18:00
  • You're working much too hard. `SET Today=%Date:~6,4%%Date:~0,2%%Date:~3,2%` works perfectly with US date formats; you can adjust the numbers in the various locations to work with your format if needed. Check the output with `echo %today%`. The numbers indicate a substring starting at X for Y characters. For instance, the first says *start at index 6 of the output of DATE and fetch 4 characters*. – Ken White Jan 12 '16 at 18:02
  • A two line batch file (separate lines at |x|) `SET Today=%Date:~6,4%%Date:~0,2%%Date:~3,2%|x|ECHO Test output > %today%.txt` leaves me with `20160112.txt` with a size of 14 bytes and a single line of text reading `Test output`. – Ken White Jan 12 '16 at 18:08

1 Answers1

5

Your final SET statement has an unwanted trailing space. This causes the redirection to become
> 2015-01-12 .txt after the variable is expanded. I think you can see now why it is failing.

Of course you can simply delete the offending space from the batch script. But there is a simple strategy that protects against inadvertent trailing characters - enclose the entire SET expression within quotes. All "normal" text after the last quote will be safely ignored, so inadvertent trailing spaces will not cause a problem. Special characters like &, |, >, etc. still have meaning after the last quote.

set "var=value" Everything after the last quote is ignored/effectively a comment

It is critical that the opening quote is before the variable name.

dbenham
  • 127,446
  • 28
  • 251
  • 390