批处理文件日期变量和输出问题 [英] Batch File Date Variable and Output Issue

查看:116
本文介绍了批处理文件日期变量和输出问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个批处理文件,它将日期格式设置为YYYYMMDD并将其存储为变量.但是,当我要生成带有文件名中日期的文本输出文件时,它将删除日期之后的所有内容.有人可以帮忙吗?在我的示例中,您会注意到您将获得一个包含文本的输出文件,但文件名将是日期,并且.txt扩展名被删除.

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

推荐答案

您的最终SET语句有多余的尾随空格.这导致重定向变为
扩展变量后的> 2015-01-12 .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.

当然,您可以简单地从批处理脚本中删除有问题的空间.但是,有一个简单的策略可以防止意外的尾随字符-将整个SET表达式括在引号中.最后一个引号之后的所有正常"文本都将被安全地忽略,因此无意的尾随空格不会造成问题.诸如&|>等特殊字符在最后引号之后仍然具有含义.

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.

这篇关于批处理文件日期变量和输出问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆