Batch File Date Variable and Output Issue

拈花ヽ惹草 提交于 2019-12-24 16:27:16

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/34750299/batch-file-date-variable-and-output-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!