Search code examples
batch-filecmd

Delete files the same size in CMD


I want to delete files the same size and retain the distinct file, but My code is not working properly. How can i fix it.

@echo off
for /r %%i in (.\*) do (
setlocal ENABLEDELAYEDEXPANSION
set /a count=0
set /a fsize=%%~zi
for /r %%j in (.\*) do (
setlocal ENABLEDELAYEDEXPANSION
if %%~zj EQU !fsize!
set /a count=count+1
if !count! GTR 1
del %%j ))
endlocal
pause

Solution

  • There are quite a few issues. Commands preceding if should be on the same line. You cannot do two delayedexpansions inside of for loops without ending them with endlocal as the expansion will run too deep.

    So you only need one delayedexpansion outside the loop. The main problem here is that you will always have a count of 2 or more in the second loop as the second for starts the recursive search again and each file will match itself, including the batch-file:

    @echo off
    setlocal enabledelayedexpansion
    for /r %%i in (*) do (
        if not "%%~i" == "%~f0" (
           set "fsize=%%~zi"
           for /r %%j in (*) do (
             if !fsize! equ %%~zj if not "%%~j" == "%%~i" if exist "%%~i" del "%%~i"
      )
     )
    )
    

    You must note however, this will recurse into the subfolders becuase of for /R So if a file exists in the root dir of 6KB as an example and a file in a subfolder also has a size of 6KB will it delete the root file and keep the file in the subfolder. It will delete all files but the last in the list with the same size.