Batch help - Check & delete if files exists

April 15, 2011 at 09:42:15
Specs: Windows Vista
Hi there

I need some help. I thought it was a pretty easy task but ive been trying to solve this all day but to no avail! I have searched through this website trying to adapt my needs but it doesnt work.
So basically I have two folders, folder 1 has all the backup files and folder 2 gets new files put in it. I need a batch file to check if the files in folder 2 have the same name in folder 1...if it does the file should be deleted from folder 2.

Heres how I thought it should be done...so I have a FOR loop with a IF statement which does the checking and if it finds the file EXISTS in folder 1 it DELETES the file from folder 2:

FOR %%a in ("C:\Users\user\Desktop\test\folder1\*.txt") DO IF EXIST "C:\Users\user\Desktop\test\folder2\*.txt" DEL %%a

Any help is appreciated and let me know if i wasnt clear...Thanks guys!


See More: Batch help - Check & delete if files exists

Report •


#1
April 15, 2011 at 10:26:59
for /f "tokens=*" %%a in ('dir C:\Users\user\Desktop\test\folder1\*.txt /b') DO DEL %%a

Use a DIR because if the file does not exist it will not show in your loop.


Report •

#2
April 15, 2011 at 10:32:17
Thanks for the reply. I cant see how files are compared with folder 2...can you explain to me please. Thanks!

Report •

#3
April 15, 2011 at 10:59:44
dir C:\Users\user\Desktop\test\folder1\*.txt /b

This will give a list of *.txt files. The /b just lists it in simple listinge so you can do work on the listing. The for loop loops through the list and runs what is after the DO and the result of the list is in %%a so you can execute the del command on it.

If you want to delete from folder 2 then you need to specify it in your delete...

for /f "tokens=*" %%a in ('dir C:\Users\user\Desktop\test\folder1\*.txt /b') DO DEL C:\Users\user\Desktop\test\folder2\%%a

If the file does not exist in folder 2 then it will simply do nothing so you don't need the if exists.


Report •

Related Solutions

#4
April 19, 2011 at 14:25:16
Excellent. Thank you...just what i wanted! Cheers mate!

Report •


Ask Question