Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
626 views
in Technique[技术] by (71.8m points)

windows - Generate unique file name with timestamp in batch script

In my .bat file I want to generate a unique name for files/directories based on date-time.

e.g.

Build-2009-10-29-10-59-00

The problem is that %TIME% won't do because it contains characters that are illegal in filename (e.g. :).

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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

EDIT: 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

It yields something like 20120730203126.530000+120 and you can use that to construct your file names.


(Old answer below)

You can simply replace the offending character with an empty string:

echo %time::=%

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%

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...