Sara Jones
Sara Jones

Reputation: 21

Batch_ Compare two similarly named files and delete the larger, multiple times

I'm looking for a nifty script that will compare file sizes when I feed it multiple files, and then delete the larger file.

I have a set of identical image files in JPG and PNG formats, and I only want to keep the smaller of the two for each individual image. Each image is similarly named, like image-01.jpg and image-01.png are pairs, image-02.jpg and image-02.png are pairs, and so on. Some images exist only as PNG (i.e. image-03.png exists, but image-03.jpg doesn't), and these should not be deleted or compared to "the next image".

Names may vary, but a set is usually quite uniform. Because there are hundreds of files to compare at once, if I had to feed it only two and two images it'd be faster to just compare them all manually, which is what I currently do.

Upvotes: 0

Views: 752

Answers (1)

Sara Jones
Sara Jones

Reputation: 21

I got some help and added a line to the code I posted in an earlier comment. I also polished the code a bit.

The following code worked for my issue. Just drop files into the code, and it will delete the largest file whenever two files have equal names. Note that files need to be passed in sorted order for it to work properly. I have no idea of how to write an efficient sorting algorithm for the arguments. This is hardly an issue got my use, though if someone wants to write one for a challenge I'd be more than happy to see it.

@echo off

:BEGIN
if "%~2" == "" goto END
echo Comparing %~n1 and %~n2...
if not "%~n1" == "%~n2" ( echo Names don't match. ) && goto NOMATCH
echo Names match! Comparing filesize...
if %~z1 gtr %~z2 (
    ( echo *** Keeping %~2 ^(%~z2 bytes^) *** )
    ( echo *** Deleting %~1 ^(%~z1 bytes^) *** )
    del "%~1".
) else (
    ( echo *** Keeping %~1 ^(%~z1 bytes^) *** )
    ( echo *** Deleting %~2 ^(%~z2 bytes^) *** )
    del "%~2".
)
:NOMATCH
echo.
shift
goto BEGIN
:END
pause

Upvotes: 1

Related Questions