파일 이름의 배치 명령 날짜 및 시간
명령 줄에서 WinZip 을 사용하여 파일을 압축하고 있습니다 . 우리는 매일 아카이브하기 때문에 매번 새 파일이 자동 생성되도록 이러한 파일에 날짜와 시간을 추가하려고합니다.
다음을 사용하여 파일 이름을 생성합니다. 복사하여 명령 줄에 붙여 넣으면 날짜 및 시간 구성 요소가있는 파일 이름이 표시됩니다.
echo Archive_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.zip
산출
Archive_20111011_ 93609.zip
그러나 내 문제는 AM 대 PM 입니다. AM 타임 스탬프는 자연스럽게 두 공간을 차지하는 대신 시간 9(앞에 공백이 있음)을 제공 10합니다.
내 문제는 처음 9 일, 처음 9 개월 등으로 확장 될 것 같습니다.
선행 공백 대신 선행 0이 포함되도록이 문제를 해결하려면 어떻게해야 Archive_20111011_093609.zip합니까?
또 다른 해결책 :
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set datetime=%%I
로케일 설정과 관계없이 다음을 제공합니다.
20130802203023.304000+120
( YYYYMMDDhhmmss.<milliseconds><always 000>+/-<timedifference to UTC> )
여기에서 쉽습니다.
set datetime=%datetime:~0,8%-%datetime:~8,6%
20130802-203023
파일의 "수정 된 날짜-시간"에 대해 동일한 출력 형식에 대한 Logan의 요청 :
for %%F in (test.txt) do set file=%%~fF
for /f "tokens=2 delims==" %%I in ('wmic datafile where name^="%file:\=\\%" get lastmodified /format:list') do set datetime=%%I
echo %datetime%
전체 경로에서만 작동 wmic하고 백 슬래시가 두 배가 될 것으로 예상하고 이스케이프해야하기 때문에 조금 더 복잡 =합니다 (첫 번째 것은 따옴표로 보호됩니다).
시간을 추출하고 선행 공백을 찾으십시오. 발견되면 0으로 대체하십시오.
set hr=%time:~0,2%
if "%hr:~0,1%" equ " " set hr=0%hr:~1,1%
echo Archive_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%hr%%time:~3,2%%time:~6,2%.zip
검색해야합니다. 당신은 단순히 0으로 모든 공백을 대체 할 수
set hr=%hr: =0%- 젭 14시 16분에서 10월 11일 '11
그래서 나는 :
set hr=%time:~0,2%
set hr=%hr: =0%
그런 다음 %hr%항상 두 자리 시간을 얻으려면 형식화하는 문자열 내부를 사용하십시오 .
(가장 인기있는 답변 아래에있는 Jeb의 댓글이 저에게 가장 효과적이었고 가장 간단합니다. 향후 사용자에게 더 명확하게 알리기 위해 여기에 다시 게시합니다.)
비키 이미 지적으로 %DATE%그리고 %TIME%완전히 (끝없이) 사용자 정의 할 수 있습니다 간단한 날짜 및 시간 형식을 사용하여 현재 날짜와 시간을 반환합니다.
한 사용자는 Fri040811 08.03PM을 반환하도록 시스템을 구성하고 다른 사용자는 08/04/2011 20:30을 선택할 수 있습니다.
BAT 프로그래머에게는 완전한 악몽입니다.
형식을 확고한 형식으로 변경하면 BAT 파일을 떠나기 전에 이전 형식으로 복원하면 문제가 해결 될 수 있습니다. 그러나 취소 된 BAT 파일에서 불쾌한 경쟁 조건과 복구가 복잡해질 수 있습니다.
다행히도 대안이 있습니다.
대신 WMIC를 사용할 수 있습니다. WMIC Path Win32_LocalTime Get Day,Hour,Minute,Month,Second,Year /Format:table날짜와 시간을 변하지 않는 방식으로 반환합니다. FOR /F명령 으로 직접 구문 분석하는 것이 매우 편리합니다 .
그래서, 조각들을 모아서 이것을 시작점으로 시도하십시오 ...
SETLOCAL enabledelayedexpansion
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
SET /A FD=%%F*1000000+%%D*100+%%A
SET /A FT=10000+%%B*100+%%C
SET FT=!FT:~-4!
ECHO Archive_!FD!_!FT!.zip
)
귀하의 모든 답변을 읽은 후 나에게 가장 적합한 솔루션을 찾았습니다.
set t=%date%_%time%
set d=%t:~10,4%%t:~7,2%%t:~4,2%_%t:~15,2%%t:~18,2%%t:~21,2%
echo hello>"Archive_%d%"
내가 얻는 경우 20160915_ 150101(선행 공백과 시간 포함).
PM이면 20160915_2150101.
다음과 같이 변수에 선행 0을 추가 할 수 있습니다 (최대 99 개의 값). IF 1%Var% LSS 100 SET Var=0%Var%
따라서 날짜 및 시간 구성 요소를 별도의 변수로 구문 분석하고 모두 이와 같이 처리 한 다음 다시 연결하여 파일 이름을 만들어야합니다.
그러나 날짜 및 시간을 구문 분석하는 기본 방법은 시스템 로케일 설정에 따라 다릅니다. 코드를 다른 컴퓨터로 이식 할 수없는 것이 만족 스러우면 괜찮지 만 다른 국제 컨텍스트에서 작동 할 것으로 예상되는 경우 레지스트리 설정을 읽는 것과 같은 다른 접근 방식이 필요합니다.
HKEY_CURRENT_USER\Control Panel\International\iDate
HKEY_CURRENT_USER\Control Panel\International\iTime
HKEY_CURRENT_USER\Control Panel\International\iTLZero
(마지막 것은 시간에 선행 0이 있는지 여부를 제어하지만 내가 아는 한 날짜는 아닙니다).
@For /F "tokens=1,2,3,4 delims=/ " %%A in ('Date /t') do @(
Set DayW=%%A
Set Day=%%B
Set Month=%%C
Set Year=%%D
Set All=%%D%%B%%C
)
"C:\Windows\CWBZIP.EXE" "c:\transfer\ziptest%All%.zip" "C:\transfer\MB5L.txt"
이것은 MB5L.txt를 가져와 2012 년 2 월 4 일에 실행하는 경우 ziptest20120204.zip으로 압축합니다.
위의 답변에서 즉시 사용 가능한 기능을 만들었습니다.
프랑스어 로컬 설정으로 확인되었습니다.
:::::::: PROGRAM ::::::::::
call:genname "my file 1.txt"
echo "%newname%"
call:genname "my file 2.doc"
echo "%newname%"
echo.&pause&goto:eof
:::::::: FUNCTIONS :::::::::
:genname
set d1=%date:~-4,4%
set d2=%date:~-10,2%
set d3=%date:~-7,2%
set t1=%time:~0,2%
::if "%t1:~0,1%" equ " " set t1=0%t1:~1,1%
set t1=%t1: =0%
set t2=%time:~3,2%
set t3=%time:~6,2%
set filename=%~1
set newname=%d1%%d2%%d3%_%t1%%t2%%t3%-%filename%
goto:eof
질문이 해결 된 것 같지만 ...
문제에 대한 올바른 해결책을 선택했는지 잘 모르겠습니다.
실제 프로젝트 코드를 매일 압축하려고한다고 가정합니다.
It's possible with ZIP and 1980 this was a good solution, but today you should use a repository system, like subversion or git or ..., but not a zip-file.
Ok, perhaps it could be that I'm wrong.
I realise this is a moot question to the OP, but I just brewed this, and I'm a tad proud of myself for thinking outside the box.
Download gawk for Windows at http://gnuwin32.sourceforge.net/packages/gawk.htm .... Then it's a one liner, without all that clunky DOS batch syntax, where it takes six FOR loops to split the strings (WTF? That's really really BAD MAD AND SAD! ... IMHO of course)
If you already know C, C++, Perl, or Ruby then picking-up AWK (which inherits from the former two, and contributes significantly to the latter two) is a piece of the proverbial CAKE!!!
The DOS Batch command:
echo %DATE% %TIME% && echo %DATE% %TIME% | gawk -F"[ /:.]" "{printf(""""%s%02d%02d-%02d%02d%02d\n"""", $4, $3, $2, $5, $6, $7);}"
Prints:
Tue 04/09/2012 10:40:38.25
20120904-104038
Now that's not quite the full story... I'm just going to be lazy and hard-code the rest of my log-file-name in the printf statement, because it's simple... But if anybody knows how to set a %NOW% variable to AWK's output (yeilding the guts of a "generic" now function) then I'm all ears.
EDIT:
A quick search on Stack Overflow filled in that last piece of the puzzle, Batch equivalent of Bash backticks.
So, these three lines of DOS batch:
echo %DATE% %TIME% | awk -F"[ /:.]" "{printf(""""%s%02d%02d-%02d%02d%02d\n"""", $4, $3, $2, $5, $6, $7);}" >%temp%\now.txt
set /p now=<%temp%\now.txt
echo %now%
Produce:
20120904-114434
So now I can include a datetime in the name of the log-file produced by my SQL Server installation (2005+) script thus:
sqlcmd -S .\SQLEXPRESS -d MyDb -e -i MyTSqlCommands.sql >MyTSqlCommands.sql.%now%.log
And I'm a happy camper again (except life was still SOOOOO much easier on Unix).
As others have already pointed out, the date and time formats of %DATE% and %TIME% (as well as date /T and time /T) are locale-dependent, so extracting the current date and time is always a nightmare, and it is impossible to get a solution that works with all possible formats since there are hardly any format limitations.
But there is another problem with a code like the following one (let us assume a date format like MM/DD/YYYY and a 12 h time format like h:mm:ss.ff ap where ap is either AM or PM and ff are fractional seconds):
rem // Resolve AM/PM time:
set "HOUR=%TIME:~,2%"
if "%TIME:~-2%" == "PM" if %HOUR% lss 12 set /A "HOUR+=12"
if "%TIME:~-2%" == "AM" if %HOUR% equ 12 set /A "HOUR-=12"
rem // Left-zero-pad hour:
set "HOUR=0%HOUR%"
rem // Build and display date/time string:
echo %DATE:~-4,4%%DATE:~0,2%%DATE:~3,2%_%HOUR:~-2%%TIME:~3,2%%TIME:~6,2%
Each instance of %DATE% and %TIME% returns the date or time value present at the time of its expansion, therefore the first %DATE% or %TIME% expression might return a different value than the following ones (you can prove that when echoing a long string containing a huge amount of such, preferrably %TIME%, expressions).
You could improve the aforementioned code to hold a single instance of %DATE% and %TIME% like this:
rem // Store current date and time once in the same line:
set "CURRDATE=%DATE%" & set "CURRTIME=%TIME%"
rem // Resolve AM/PM time:
set "HOUR=%CURRTIME:~,2%"
if "%CURRTIME:~-2%" == "PM" if %HOUR% lss 12 set /A "HOUR+=12"
if "%CURRTIME:~-2%" == "AM" if %HOUR% equ 12 set /A "HOUR-=12"
rem // Left-zero-pad hour:
set "HOUR=0%HOUR%"
rem // Build and display date/time string:
echo %CURRDATE:~-4,4%%CURRDATE:~0,2%%CURRDATE:~3,2%_%HOUR:~-2%%CURRTIME:~3,2%%CURRTIME:~6,2%
But still, the returned values in %DATE% and %TIME% could reflect different days when executed at midnight.
The only way to have the same day in %CURRDATE% and %CURRTIME% is this:
rem // Store current date and time once in the same line:
set "CURRDATE=%DATE%" & set "CURRTIME=%TIME%"
rem // Resolve AM/PM time:
set "HOUR=%CURRTIME:~,2%"
if "%CURRTIME:~-2%" == "PM" if %HOUR% lss 12 set /A "HOUR+=12"
if "%CURRTIME:~-2%" == "AM" if %HOUR% equ 12 set /A "HOUR-=12"
rem // Fix date/time midnight discrepancy:
if not "%CURRDATE%" == "%DATE%" if %CURRTIME:~0,2% equ 0 set "CURRDATE=%DATE%"
rem // Left-zero-pad hour:
set "HOUR=0%HOUR%"
rem // Build and display date/time string:
echo %CURRDATE:~-4,4%%CURRDATE:~0,2%%CURRDATE:~3,2%_%HOUR:~-2%%CURRTIME:~3,2%%CURRTIME:~6,2%
Of course the occurrence of the described problem is quite improbable, but at one point it will happen and cause strange unexplainable failures.
The described problem cannot occur with the approaches based on the wmic command as described in the answer by user Stephan and in the answer by user PA., so I strongly recommend to go for one of them. The only disadvantage of wmic is that it is way slower.
A space is legal in file names. If you put your path and file name in quotes, it may just fly. Here's what I'm using in a batch file:
svnadmin hotcopy "C:\SourcePath\Folder" "f:\DestPath\Folder%filename%"
It doesn't matter if there are spaces in %filename%.
참고URL : https://stackoverflow.com/questions/7727114/batch-command-date-and-time-in-file-name
'Program Club' 카테고리의 다른 글
| 모든 열거 형 값을 배열로 가져옵니다. (0) | 2020.11.19 |
|---|---|
| Python에서 함수 호출의 실행 시간을 제한하는 방법 (0) | 2020.11.19 |
| Spring MVC의 뷰 기술로 JSF 사용 (0) | 2020.11.19 |
| RSpec : 여러 변경 예상 (0) | 2020.11.19 |
| webdesign-웹에 가장 적합한 jpg 또는 png (0) | 2020.11.19 |