1

I have a tree of directories containing files and sometime a copy at the same location. This copy is identified by some string, e.g. _001, appended to the original file name.

  • somefile.txt and
  • somefile_001.txt

I can list such files at the DOS prompt using: dir /s *_001.*

or

for /f "tokens=1,2 delims=_" %i in ('dir /s /b *_*.*') do echo %i_%j

But I don't know if this is possible, likely using the later format, to check whether the original file exists and in this case delete the copy.

1 Answer 1

2

Your command is pretty close. Try this:

for %i in (*) do if exist "%~ni_001%~xi" echo del "%~ni_001%~xi"

Check a few of the resulting del statements for testing to prove that the correct files are being deleted, then remove the 'echo' for the deletion to actually happen. Or, redirect the output to a file of del statements and check that.

The %~ n and x stuff is explained towards the end of a 'help for' command.

EDIT: the %xi doesn't need a . in front of it as the . is part of the extension returned by %~xi. Fixed.

EDIT2: Changed 'del %i' to current form as I misread the original question and thought the checked-for file was to be deleted, not the _001 copy. Also, added quotes for filenames-with-spaces protection.

4
  • Thanks a lot! Works (pls ignore my previous comment, now deleted). I was not aware of IF EXIST. As regard to the FOR command I didn't know it until recently, and I see that this is a powerful tool. Your help has been appreciated. I have modified a little to be recursive, and to allow for spaces in path: for /R %i in (*) do if exist %~pi%~ni_001%~xi echo del "%~pi%~ni_001%~xi" >>deleted.txt
    – mins
    Aug 1, 2014 at 15:40
  • Good work! Heh, I deleted first comment reply, too. I added quote protection around the constructed filename in the 'if exist' clause. Spaces in the filename could possibly result in an incorrect 'if' statement there, too. Corrected answer to reflect that.
    – james
    Aug 1, 2014 at 16:40
  • @mins This approach might not optimal, especially if the total number of files you need to inspect is non-trivial (e.g. thousands). Assuming the amount of files (e.g. somefile.txt) is higher or equal to the amount of copies (e.g. somefile_001.txt), you can avoid checking every single file by filtering them beforehand. Here's an example script: pastebin.com/gp38WMPV
    – and31415
    Aug 3, 2014 at 13:14
  • @and31415: thanks, that was the way I tried to find initially.
    – mins
    Aug 15, 2014 at 19:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .