Delete files in folder B which exist in folder A

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Yanta
Posts: 48
Joined: 01 Sep 2019 07:08

Delete files in folder B which exist in folder A

#1 Post by Yanta » 28 Aug 2021 05:02

I have two folders. Folder B contains 300 files. The complete set.
Folder A contains a subset of folder B. About 120 files.
I want to delete the files in folder B that exist in folder A
Essentially, folder A is a list of files that are safe to be deleted from Folder B.

If it's any easier, I can simply write the file names to a text file for folder A then delete any files in Folder B if the filename exists in the text file.
Which ever is easier.

How would I do this?

Squashman
Expert
Posts: 4315
Joined: 23 Dec 2011 13:59

Re: Delete files in folder B which exist in folder A

#2 Post by Squashman » 28 Aug 2021 12:22

Based on your previous questions I see no reason why you shouldn't be able to figure this out yourself. This could literally be written in one line of code. A simple for command to iterate the files in one directory and use that output with the delete command.

Yanta
Posts: 48
Joined: 01 Sep 2019 07:08

Re: Delete files in folder B which exist in folder A

#3 Post by Yanta » 28 Aug 2021 19:54

Thanks.
Couldn't figure it out so I've had to code 150 lines in my batch file instead.

AR Coding
Posts: 20
Joined: 02 May 2021 21:16

Re: Delete files in folder B which exist in folder A

#4 Post by AR Coding » 28 Aug 2021 20:49

This might work

Code: Select all

for /f %%a in ('dir C:\FolderA\* /b /s') do (
 for /f %%A in ('dir C:\FolderB\* /b /s') do (
  if exist "%%a" del "%%A"
 )
)
obviously Dont forget to change the folder nameS

Squashman
Expert
Posts: 4315
Joined: 23 Dec 2011 13:59

Re: Delete files in folder B which exist in folder A

#5 Post by Squashman » 28 Aug 2021 22:40

Code: Select all

for %%G in ("C:\FolderA\*") do del "C:\FolderB\%%~nxG" 2>nul

Squashman
Expert
Posts: 4315
Joined: 23 Dec 2011 13:59

Re: Delete files in folder B which exist in folder A

#6 Post by Squashman » 28 Aug 2021 22:43

AR Coding wrote:
28 Aug 2021 20:49
This might work

Code: Select all

for /f %%a in ('dir C:\FolderA\* /b /s') do (
 for /f %%A in ('dir C:\FolderB\* /b /s') do (
  if exist "%%a" del "%%A"
 )
)
obviously Dont forget to change the folder nameS
%%a will always exist if the working directory is folder A because the first for command created it. You also have to remember that the folder path is not included in the FOR variable when capturing the dir output.

Post Reply