问题描述
在我的.bat文件我想要生成基于日期时间的文件/目录的唯一名称。
In my .bat file I want to generate a unique name for files/directories based on date-time.
例如
Build-2009-10-29-10-59-00
问题是,%TIME%不会做,因为它包含在文件名非法字符(如:)。
The problem is that %TIME% won't do because it contains characters that are illegal in filename (e.g. ':').
有没有在批处理文件中像'TR'?
Is there something like 'tr' in batch files?
任何其他的想法如何解决这个(不从批间preTER需要额外的命令行实用程序除外)?
Any other ideas how to solve this (that don't require extra command line utilities aside from the batch interpreter)?
推荐答案
编辑:这样做的更好的方法是采取具有确定不变的格式,而不是使用语言环境定义那些从一个日期/时间字符串%DATE%
和%TIME%
。您可以使用以下方法来得到它:
A better way of doing this is to take a date/time string that has a defined and unchanging format instead of using the locale-defined ones from %date%
and %time%
. You can use the following to get it:
for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined mydate set mydate=%%x
它会产生类似 20120730203126.530000 + 120
键,你可以用它来构建你的文件名。
It yields something like 20120730203126.530000+120
and you can use that to construct your file names.
(下旧的答案)
您可以简单地用一个空字符串替换有问题的字符:
You can simply replace the offending character with an empty string:
echo %time::=%
语法%VAR如:str1 = STR2赛车%
需要环境变量(或伪变量%TIME%并替换
STR1 > STR2
。如果没有遵循之后等号再签收 STR1
只是删除。
The syntax
%var:str1=str2%
takes the environment variable (or pseudo-variable in case of %TIME%
and replaces str1
by str2
. If nothing follows after the equals sign then str1
is simply deleted.
在您的具体情况下,我想你会希望以下内容:
In your specific case I think you'd want the following:
rem cut off fractional seconds
set t=%time:~0,8%
rem replace colons with dashes
set t=%t::=-%
set FileName=Build-%date%-%t%
一个更强力的方式的情况下,你不知道是否使用冒号(但时间顺序将是相同的):
A more brute-force way in case you don't know whether colons are used (but the order of the time would be the same):
set FileName=Build-%date%-%time:~0,2%-%time:~3,2%-%time:~6,2%
所有preceding的事情,但是,假设你使用标准的ISO 8601日期格式,我。即2009-10-29。我以为这只是为正常,但是有些人使用其他格式的,所以要小心。但因为你并没有问我是假设你没有有问题存在的日期。
All preceding things, however, assume that you use standard ISO 8601 date format, i. e. 2009-10-29. I'd assume this as simply normal, but some people use other formats so be careful. But since you didn't ask about the date I was assuming you didn't have a problem there.
这篇关于生成唯一的文件名与批处理脚本时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!