简体   繁体   中英

Batch File Date Variable and Output Issue

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM