1

I have a question regarding deleting the oldest file after a folder gets an X amount of files with the same extension, in this case, all the files share in common the extension *.bak, they are small files that I create for my firefox RES, they have imprinted on the title, the date and hour of creation, and that's as far as I can go.

Anyways, I've stumbled across this: Batch Script to delete oldest folder in a given folder. And I'm struggling to get it to work on my idea.

The thing is that I want the batch to simply check which file is the oldest after it creates a new one using this simple line of code.

copy /y store.json "%DROPBOX%\RES BACKUPS\store.json %date:~-4,4%-%date:~-7,2%-%date:~-10,2%_%time:~0,2%hs-%time:~3,2%min-%time:~6,2%s.bak"
Community
  • 1
  • 1

1 Answers1

6

You can use this:

@echo off
for /f "delims=" %%a in ('dir /b /a-d /t:w /o:d "%DROPBOX%\RES BACKUPS\*.bak"') do (
    del "%%a"
    goto :breakLoop
    )
:breakLoop

I suggest first testing it with echo del "%%a" to make sure it deletes the right file.

This works by getting the output of the dir command, which shows all files in bare format (only filenames, not sizes etc.) sorted by oldest files first. It then deletes the first file found, and breaks the loop.

A version that keeps deleting files while there are more than a specific amount:

@echo off
set "source=%DROPBOX%\RES BACKUPS\*.bak"
set "minFiles=5"
for /f %%A in ('dir "%source%" /a-d-s-h /b ^| find /v /c ""') do if %%A leq %minFiles% goto :eof
:loop
for /f "delims=" %%a in ('dir /b /a-d /t:w /o:d "%source%"') do (
    del "%%a"
    goto :breakLoop
    )
:breakLoop
for /f %%A in ('dir "%source%" /a-d-s-h /b ^| find /v /c ""') do if %%A gtr %minFiles% goto :loop
pause

You can make this non-looping (but still only delete if there are more than 5) by removing the line for /f %%A in ('dir "%source%" /a-d-s-h /b ^| find /v /c ""') do if %%A gtr %minFiles% goto :loop

Dennis van Gils
  • 3,487
  • 2
  • 14
  • 35
  • Hi! Thanks for the answer, It's too much to ask a little explanation on what does the code do? Or a page where I can read about it, so I can learn at the same time. I'll test it out to see what happends. – Francisco Laferrière Feb 24 '16 at 22:13
  • @FranciscoLaferrière added explanation – Dennis van Gils Feb 24 '16 at 22:14
  • @"Dennis van Gils" Aaah, I see, and all I have to do now is to make a few more backups to reach my "desired amount" of actual backups that I have, because If I understand correctly, there's no "IF" statement that tells if there's more files than wanted. Am I right? – Francisco Laferrière Feb 24 '16 at 22:18
  • To simplify the logic, I moved `:loop` above the first `for`, changed `goto :breakLopp` to `goto :loop`, removed `:breakLoop`, and changed last `for` to `goto :loop`. With this, the logic is: if there are more than 5 files, remove one and repeat. – Alexander Gelbukh Aug 26 '17 at 00:04