Question

I'm searching a way to keep the latest N files in a directory, removing the old ones.

I got a daily backup that comes by FTP in a folder (Windows Server) and i would like to just keep the last 3 backups. Those backups comes in 2 files (the first one .tar.gz and the second is a MySQL dump .sql).

The point is that those backups may not come on some days, so I dont just want to delete the files older than 3 days. But delete as much files as possibile, to just keep the newest 6 files (3 days of bacups, 2 files at once).

How to do this with a .bat ?

Thanks in advance

Was it helpful?

Solution

A bit more straight forward than Endoro's answer. This assumes that the .sql and .tar.gz files always come in pairs.

for /f "skip=6 eol=: delims=" %%F in ('dir /b /a-d /o-d *.tar.gz *.sql') do del "%%F"

Explanation:

The DIR command lists the files sorted by last-modified time stamp in descending order. Type help dir or dir /? from the command prompt to get documentation on what all the options mean. The FOR command processes the results. The SKIP option skips the first 6 files, which happens to be the files you want to keep since they sort to the top. The remaining file names are passed to the DEL command. Type help for or for /? for documentation on FOR - it is a bit of a beast, with many options.

OTHER TIPS

try this:

for /f "tokens=1*delims=:" %%a in ('dir /b /a-d /o-d *.tar.gz *dump.sql 2^>nul^|findstr /n "^"') do if %%a gtr 6 echo del "%%~b" 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top