1

I want to write a batch file that will remove the file overlap between two folders.

In other words, I want it to say "Remove from folder A all files which also appear in folder B".

From a SQL point of view, it would be something like

DELETE FROM FOLDERA WHERE EXISTS(SELECT FILE FROM FOLDERB) 

but I want to accomplish that in the windows filesystem.

3 Answers 3

2

Answering my own question:

set if_it_exists_here=C:\folderB set then_delete_it_there=C:\folderA cd "%if_it_exists_here%" FOR /F "tokens=*" %%G IN ('dir *.* /b /a:-d') DO del "%then_delete_it_there%\%%G" 
Sign up to request clarification or add additional context in comments.

2 Comments

i suppose its given that the file ALWAYS exists in both folderA and folderB?
No, not necessarily. If there is no overlap, then the script will not delete anything.
1
SET if_it_exists_here=C:\folderB SET then_delete_it_there=C:\folderA CD "%if_it_exists_here%" FOR %%A IN (*.*) DO ( IF EXIST "%then_delete_it_there%\%%~nxA" DEL /Q /F %then_delete_it_there%\%%~nxA ) 

3 Comments

This is an interesting alternative. Is there any special advantage to this approach?
This just looks for the file before deleting it as opposed to assuming the file exists and deleting it. So redirecting with 2> should come out clean. I always test with redirecting 2> file > file2 to ensure nothing goes wrong with the code, and having it return "file not found" to STDERR is annoying =/. Just nitpicky.
Great points, I think I'll use this rather than my own. I suspect it will perform better with large numbers of files, too.
0

Building on the answer by Mechaflash, here is a version that works with UNC paths.

SET if_it_exists_here=\\server1\some\folder SET then_delete_it_there=\\server2\some\folder CD "%if_it_exists_here%" FOR %%A IN ("%if_it_exists_here%\*.*") DO ( IF EXIST "%then_delete_it_there%\%%~nxA" DEL /Q /F %then_delete_it_there%\%%~nxA ) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.