0

I am trying to create a 1 line command that will get all directories matching a pattern and delete a certain number of them.

Lets say i have a directory like this:

C:/
   tmp/
       www/
          01/
          02/
          03/
          04/
          05/

And i want to only keep the latest 2 folders 05 and 04.

i have a for loop that will output all the folders, the part im having trouble with is counting past a certain amount:

> for /f "tokens=*" %G in ('dir /b /a:d "C:\tmp\www\*"') do echo Found %G
Found 20161201004853
Found 20161201005125
Found 20161201005246

I have tried adding in a counter but im not sure how to separate the commands since its all on 1 line. Despite a large amount of googling for how, im hoping someone here know.

As always if there is a better way to do this I am open to that too.

Chase
  • 103
  • 3

1 Answers1

1

This will delete all but the last 2 folders (assuming they are ordered alphabetically)

Just put that line id a .cmd/.bat file and execute inside the parent folder

. The number of files could be controled by a parameter (%1) passed to command . Deleting the last or the first folders can be controled in 'dir /b /o.n'

setlocal EnableDelayedExpansion & set x=0 & for /f %%f in ( 'dir /b /o-n' ) do ( set /a x+=1 &  if !x! lss 3 rd /s/q %%f )
ZEE
  • 326
  • 3
  • 14
  • Ill test this in the morning when i get into work, thanks for your response. Any way you can expand on that the `dir /b /o-n` is doing? Also is `rd` an alias for `rmdir`? – Chase Dec 01 '16 at 04:37
  • yes, rd is rmdir... – ZEE Dec 02 '16 at 16:58
  • /b switch is listing all files and folders in current folder returning only the file/folder fullname (including absolute path)... and /o-n switch is sorting them in reverse order (so you can delete only the first 2).... ;-) – ZEE Dec 02 '16 at 17:01