Search code examples
batch-filecmddos

How do I iterate over files/directories with names that do not match a wildcard?


From within a batch script file, the following code successfully deletes folders that begin with a name preceding *, denoting a wildcard. How do I write a FOR loop which iterates over the files/folders which don't match? eg; ![*abc]

REM Remove unwanted files/directories

FOR /D /r %%G IN ("local\partialFileName*") DO (

            RMDIR /Q /S %%G                 

)

Solution

  • Create a temp dir, move matching files there, delete all that remain, and then move them back. Since a move on the same drive doesn't require a copy, it will be fast.

    md ..\foo
    move *abc ..\foo
    rd . /s /q 
    move ..\foo\* .
    rd ..\foo
    

    The first rd command will generate an error message, but that can be ignored.