我需要一个例程来将文件重命名为转换后的文件名并删除给定目录中的原件。
它必须只查找起始字符串GL_AVG
,{{1 }},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
到目前为止,我有以下代码来解析year和filemonth,但是无法尝试使用这些变量重命名。
GL_AVG_Feb_2017.txt
GL_DEFAULT_Feb_2017.txt
GL_END_Feb_2017.txt
任何帮助都将不胜感激!
答案 0 :(得分: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"
如果输出看起来没问题,请删除最后一行的回声。
答案 1 :(得分: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