4

I have a program that automatically copies files to a directory, and if it creates a duplicate it will name it like so:

file with duplicate.xxx
file with duplicate - 1.xxx
file with duplicate - 2.xxx

I need a way to delete all the duplicates with a Windows batch file.

Something along the lines of:

FOR %f IN (C:\files\*.*) DO del "%f - 1"

However, that will not work because that would resolve to file with duplicate - 1.xxx - 1

| improve this question | | | | |
  • a)Try for /r to go through directories. b)%~nf instead of %f will get the filename without the extension – barlop Sep 12 '11 at 1:34
5

If you want to delete all the files with a name that ends in - ?, then you were close.

Try this:

FOR %%f IN ("C:\files\* - ?.*") DO del "%%f"

You will need to double up the percent signs if you are running it from a batch file. And test with an echo instead of a del first.

| improve this answer | | | | |
  • I was overthinking it, you're absolutey right... there's no reason to base it off the original file name when all duplicates are guaranteed to end in " - [some number]". Though I didn't know about the ? selector... do batch files accept regex? – Chris Sobolewski Sep 12 '11 at 1:41
  • @Chris Batch files do not accept regular expressions, the * is not a regex * and the ? is not a regex ? you probably haven't fiddled with regexes that much. a*b if it was a regex would match b since * in regex matches 0 or more of the char before. In cmd * and ? are more intuitive, * means any sequence of char, and ? means one char. – barlop Sep 12 '11 at 2:05
  • @Chris Sobolewski, regex? I wish. :) It's simple wildcards, * for any number of any character, ? for any single character. – Hydaral Sep 12 '11 at 2:07
  • @Chris furthermore, I suppose you can skip the whole FOR and just do the DEL. Since DEL can take wildcards. Interestingly DEL even has a /S switch so if you wanted to go through subdirectories, you wouldn't even need a FOR /R. – barlop Sep 12 '11 at 2:07
3

No need to the FOR, del can accept wildcards. Try:

del "c:\files\* - 1.xxx"

Will match anything with the suffix " - 1.xxx" in the directory.

| improve this answer | | | | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.