Reputation: 45
I need a routine to rename files to the converted file names and delete the original in a given directory.
It has to look for just the beginning string GL_AVG
, GL_DEFAULT
, GL_END
because after that the file name will be changing daily so can't be hardcoded, (that I can do).
Original Files:
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
Converted To:
GL_AVG_Feb_2017.txt
GL_DEFAULT_Feb_2017.txt
GL_END_Feb_2017.txt
So far, I have the following code to parse the year and filemonth, but having trouble trying to rename using these variables.
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
)
Any assistance would be appreciated!
Upvotes: 0
Views: 112
Reputation:
@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"
Sample output
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"
If the output looks ok remove the echo in the last line.
Upvotes: 2
Reputation: 64672
I would use the string-replacement function, which looks like:
%VariableName:[OldText]=[NewText]%
Or in your case:
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
Alternately, you may want to look at http://www.dostips.com/?t=Snippets.MapLookup
Upvotes: 0