views:

18

answers:

3

I have a folder with sequentially named images (a0001, a0002, a0003, etc.) and I was wondering if there was a way to delete every 3 files without touching the others.

So for example, I have: a0001, a0002, a0003, a0004, a0005 a0006, a0007, a0008, a0009

And after I would like to have: a0001, a0005, a0009

A: 

I'm not sure about the syntax, as I usualy don't write batch scripts, but should be something like:

set z = 0
for /f %%a IN (‘dir /b *’) do {
  set z = z + 1;
  if (z % 3 == 0) del %%a
}
JochenJung
A: 

Here's a vbscript you can use

strFolder = WScript.Arguments(0)
Set objFS = CreateObject( "Scripting.FileSystemObject" )
Set objFolder = objFS.GetFolder(strFolder)
i=0
For Each strFile In objFolder.Files
    If i Mod 4 <> 0 Then
        WScript.Echo strFile.Name
        objFS.DeleteFile(strFile.Name)
    End If
    i=i+1
Next

usage:

C:\test> cscript //nologo test.vbs c:\folder_to_process
ghostdog74
A: 

Here's a solution. This allows you to specify what to delete (eg c:\temp\*.tmp) how many files to skip (the default being 3 as you requested) and what order to use (the default being n - filename). You can use any DIR ordering eg N (name) or ES (extension then size), see dir /? to learn more about ordering. You shouldn't start the order command with /o (unlike dir) - it's auto-prepended.

Source: ndel.bat

@echo off
::: ndel - Deletes every nth file matching the spec
::: syntax: ndel.bat FILESPEC [skipcount] [sortorder]
:::           FILESPEC  - Files to be searched through
:::           skipcount - number of files to skip (optional - default 3)
:::           sortorder - File order (see: DIR for options - default N (name))

:: With no arguments show the above usage text
if "%~1"=="" findstr "^:::" "%~f0"&GOTO:EOF
set find=%1
set evry=4
set ord=n
if "%~2" neq "" set /a evry=(%2+1)
if "%~3" neq "" set ord=%3

set count=0
for /f %%f IN ('dir %find% /b /o%%ord%%') do (
    call :test_file "%%f"
)
GOTO:eof

:test_file
set /a _r="%count% %% %evry%"
if %_r%==0 echo %1
::-to delete- if %_r%==0 del %1
set /a count+=1
GOTO:eof

Notes:

  • You need to comment out if %_r%==0 echo %1 and remove the starting comment ::-to delete- to actually preform the delete (once you're happy it works :)).
  • The first few lines just output usage if you type in ndel (without a parameter)
  • Skip three is the same as saying delete every fourth file, which is why evry takes skip+1, and by default is set to 4 (skip 3).
  • filespec can include a folder and complicated wild-card matches (just like dir).
  • A subroutine has to be used to count properly through the for (Environment variables within a FOR loop are expanded at the beginning of the loop and won't change until after the end of the DO section)
  • Calling ndel c:\temp\*.tmp 0 is the same as del c:\temp\*.tmp (since skip 0 = all)
Rudu