2017-02-15 108 views
0

我需要一個例程來將文件重命名爲轉換後的文件名並刪除給定目錄中的原件。

它必須尋找只是開始字符串GL_AVG,GL_DEFAULT,GL_END,因爲之後,文件名將會每天更改,所以不能硬編碼,(我可以做)如何根據開始文件名重命名文件?

原始文件:

GL_AVG_2017-02-15_08-54-56.txt 
GL_DEFAULT_2017-02-15_08-54-34.txt 
GL_END_2017-02-15_08-55-12.txt 

轉換爲:

GL_AVG_Feb_2017.txt 
GL_DEFAULT_Feb_2017.txt 
GL_END_Feb_2017.txt 

到目前爲止,我有以下的代碼來解析一年filemonth,但遇到問題嘗試使用這些變量來命名。

For /F "eol=_ tokens=3 delims=_" %%a in ('dir /b *.txt') do set yy=%%~na 
For /F "eol=_ tokens=2 delims=-" %%a in ('dir /b *.txt') do set filemonth=%%~na 

if %filemonth% == "01" set mm=Dec 
if %filemonth% == "02" set mm=Jan 
if %filemonth% == "03" set mm=Feb 
if %filemonth% == "04" set mm=Mar 
if %filemonth% == "05" set mm=Apr 
if %filemonth% == "06" set mm=May 
if %filemonth% == "07" set mm=Jun 
if %filemonth% == "08" set mm=Jul 
if %filemonth% == "09" set mm=Aug 
if %filemonth% == "10" set mm=Sep 
if %filemonth% == "11" set mm=Oct 
if %filemonth% == "12" set mm=Nov 

set dd=%%c 

) 

任何援助將不勝感激!

+1

你的IF語句永遠不會是真的。這是一個字符串比較。你在比較的一側有引號,但沒有引用另一側。 – Squashman

+0

感謝您的收穫。關於重命名作品的任何想法? – user7571572

+1

你有意減去一個月嗎? – LotPings

回答

0

我會使用字符串替換功能,它看起來像:

%VariableName:[OldText]=[NewText]% 

或者你的情況:

for /F "eol=_ tokens=2 delims=-" %%a in ('dir /b *.txt') do (
    call :RenameFile %%~na) 
exit /B 

:RenameFile [%1: Name of file to be renamed] 
    set Filename=%1 

    ::Look for "2017-01", change it to "2017_Jan" 
    ::Repeat for each possible month. 
    set Filename=%Filename:2017-01=2017_Jan% 
    set Filename=%Filename:2017-02=2017_Feb% 
    set Filename=%Filename:2017-03=2017_Mar% 
    set Filename=%Filename:2017-04=2017_Apr% 
    set Filename=%Filename:2017-05=2017_May% 
    set Filename=%Filename:2017-06=2017_Jun% 
    set Filename=%Filename:2017-07=2017_Jul% 
    set Filename=%Filename:2017-08=2017_Aug% 
    set Filename=%Filename:2017-09=2017_Sep% 
    set Filename=%Filename:2017-10=2017_Oct% 
    set Filename=%Filename:2017-11=2017_Nov% 
    set Filename=%Filename:2017-12=2017_Dec% 
    rename %1 %Filename% 
exit /B 

或者,你可能想看看http://www.dostips.com/?t=Snippets.MapLookup

2
@Echo off&SetLocal EnableExtensions EnableDelayedExpansion 
:: build a pseudo array with the month names 
Set M#=101 
For %%A in (Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 
) do Set Month[!M#:~-2!]=%%A&Set /A M#+=1 
:: Rename 
For /f "tokens=1-4* delims=_-" %%A in (
    'Dir /B GL_*_20*_*.txt' 
) Do Echo Ren "%%A_%%B_%%C-%%D-%%E" "%%A_%%B_!Month[%%D]!_%%C.txt" 

取樣輸出

Ren "GL_AVG_2017-02-15_08-54-56.txt" "GL_AVG_Feb_2017.txt" 
Ren "GL_DEFAULT_2017-02-15_08-54-34.txt" "GL_DEFAULT_Feb_2017.txt" 
Ren "GL_END_2017-02-15_08-55-12.txt" "GL_END_Feb_2017.txt" 

如果輸出看起來不錯,請刪除最後一行中的回顯。