views:

1175

answers:

4

What would the Windows command line script be to rename a folder from the current month, to the current month - 3, using the format YYYY-MM ?

e.g.:

c:\myfiles\myFolder\

should become:

c:\myfiles\2009-01\

A: 

ren *-04 *-01

Suvesh Pratapa
That's correct (and I have given +1). Although I made a mistake in the question - sorry! I have now changed the source folder name in the question.
Techboy
+1  A: 

You will have to dissect the contents of %DATE% by yourself, unfortunately. There are no localization-safe date/time manipulation facilities in cmd.

For my locale (which uses standard ISO 8601 date format) I could just use the following:

@echo off
rem %DATE% comes back in ISO 8601 format here, that is, YYYY-MM-DD
set Y=%DATE:~0,4%
set /a M=%DATE:~5,2% - 3
if %M% LSS 1 (
    set /a Y-=1
    set /a M+=12
)
ren myFolder "%Y%-%M%"

However, depending on the date format you use it may look slightly different.

Joey
+2  A: 

For my locale, I need something different.

Also you need to deal with single-digit months, I suppose.

setlocal
@REM example:  Thu 06-11-2009
set stamp=%DATE%

@REM get the year
set year=%stamp:~10,4%
@REM example: 2009

@REM get the month
set month=%stamp:~4,2%
@REM example:  06

@REM subtract 3 months
set /a month=%month%-3
@REM example:  3

@REM test if negative (we rolled back beyond January 1st)
if %month% LSS 1  (
  set /a month=%month%+12
  @REM example: 8
  set /a year=%year%-1
  @REM example: 2008
)

@REM prepend with zero for single-digit month numbers
set month=0%month%

@REM take last 2 digits of THAT
set month=%month:~-2%

set newFolder=%year%-%month%

@REM move %1 %newFolder%
endlocal
Cheeso
Thank you very much!I just had to tweak it for the UK date format (I should have mentioned that in the question). I'll post the UK version of your answer too. Plus I had to define %1 as the source folder.
Techboy
A: 

The version of the answered question for UK date format (DD-MM-YYYY) is:

setlocal

@REM example: 11-06-2009
set stamp=%DATE%
@REM get the year

set year=%stamp:~6,4%
@REM example: 2009
@REM get the month

set month=%stamp:~3,2%
@REM example: 06

@REM subtract 3 months
set /a month=%month%-3
@REM example: 3

@REM test if negative (we rolled back beyond 1st January)
if %month% LSS 1 (
set /a month=%month%+12
@REM example: 8

set /a year=%year%-1
@REM example: 2008
)

@REM prepend with zero for single-digit month numbers
set month=0%month%

@REM take last 2 digits of THAT
set month=%month:~-2%

set newFolder=%year%-%month%

move c:\myfiles\myFolder\ %newFolder%

endlocal

Techboy