在批处理脚本中生成带有时间戳的唯一文件名 [英] Generate unique file name with timestamp in batch script

查看:21
本文介绍了在批处理脚本中生成带有时间戳的唯一文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 .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?

任何其他的想法如何解决这个问题(除了批处理解释器不需要额外的命令行实用程序)?

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 by 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%

然而,所有前面的事情都假设您使用标准 ISO 8601 日期格式,即.e.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.

这篇关于在批处理脚本中生成带有时间戳的唯一文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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