Jordi Castilla
Jordi Castilla

Reputation: 26961

Batch loop over folder names sorting by date ignoring newer N elements

So, I have to make a batch in windows (.bat) to delete old folders in a backup disk.

I've made a script to delete folders individually:

delete_single_folder.bat

@echo off
if %1.==. goto usage
if exist %1\nul goto deldir
echo Folder %1 does not exists.
goto end
::------------------------------------------------
:deldir
rd /s/q %1
echo Folder %1 deleted.
goto :end
::------------------------------------------------
:usage
echo usage:
echo   %0 DIRNAME
echo.
echo Deletes the directory named DIRNAME and everything in it if it exists!
echo.
:end

As you can see in ::usage it's executed via delete_single_folder FOLDER_TO_DELETE. Great.


Now, I get all folders sorted by date descending with:

dir /ad /b /O-D

And delete selected folders with a for-loop:

for /f %%i in ('dir /ad /b /O-D') do ( 
     delete_single_folder %%i
)

That works great, problem is deleting ALL folders, and I want to ignore N records (days).

ACTUAL OUTPUT for dir /ad /b /O-D

20160211
20160210
20160209
20160208
20160207
20160206
20160205
20160204
20160203
20160202
20160201
20160131

But I want something like: dir /ad /b /O-D /ignore_first_5

EXPECTED OUTPUT:

20160206
20160205
20160204
20160203
20160202
20160201
20160131

Upvotes: 2

Views: 1597

Answers (1)

prudviraj
prudviraj

Reputation: 3744

we can get that working by using skip option in for command.

syntax :

for /f "tokens=* skip=4" %a in ('dir /ad /b /O-D') do echo %a

Above command would skip first four folders from the output.

you can tweak the command according to your requirement

changes made to your code to get it working :

for /f "tokens=* skip=5" %%i in ('dir /ad /b /O-D') do ( 
 echo %%i
)

replace echo %%i with RD to delete folders , once you feel it is working as expected

Upvotes: 3

Related Questions