Windows: compare files in folders and delete non existent

3k views Asked by At

I have huge directories + subdirs containing files on Windows. On the windows command line (or through a script) I'd like to compare two folders and delete files from the subfolder that are not in the main folder.

In the example below the even numbered files should be deleted from the subfolder.

folder: C:\folder1
    file1.jpg
    file3.jpg
    file4.jpg
    file7.jpg
    file9.jpg

subfolder: C:\folder1\RAW\
    file1.CR2
    file2.CR2
    file3.CR2
    file4.CR2
    file5.CR2
    file6.CR2
    file7.CR2
    file8.CR2
    file9.CR2

I have tried several scripts I found here, but non of them do the job. Any help is appreciated!

2

There are 2 answers

0
KJS On BEST ANSWER

Thanks for the input everyone, I came up with a solution also thanks to your input. It works perfect when using it on the command line (Windows of course).

View list before delete:

for %F in ("C:\folder1\RAW\*.CR2") do @if not exist "C:\folder1\%~nF.jpg" echo del "%F"

To delete, remove 'echo'

for %F in ("C:\folder1\RAW\*.CR2") do @if not exist "C:\folder1\%~nF.jpg" del "%F"

Hope this will be of use for some out there as well!

0
MC ND On
@echo off
    setlocal enableextensions disabledelayedexpansion

    set "folder=c:\folder1\raw"

    for %%a in ("%folder%\*") do (
        dir /a-d "%%~dpa..\%%~na.*" >nul 2>&1 || echo del "%%~fa"
    )

for each file in the indicated folder if a file with the same name does not exist in the parent folder, remove from child (dir command is used instead of if exists to avoid false positive match with folder names)

Delete operations are only echoed to console. If the output is correct, remove the echo command