Search code examples
windowsbatch-filecmddirectoryrmdir

Batch script to delete all folders except of "Starts with"


I have a folder with several subfolders. Structure is like:

  • C:\foo
  • C:\foo\web.foo
  • C:\foo\web.bar
  • C:\foo\win.foo
  • C:\foo\win.bar
  • C:\foo\mobile.foo
  • C:\foo\mobile.bar

I sometimes wish to delete the folders with its containing files with following batch script:

rmdir C:\foo /s /q

Here it didn't matter that the whole folder C:\foo was deleted completely.

But now I only want to delete only the subfolders of C:\foo with its containing files, which DO NOT start with "web.".

Do you have any good solution for this?


Solution

  • The following should do the trick, note it's a batch file using the current directory:

    @echo off
    for /F "delims=" %%D in ('dir /B /AD ^| findstr /V "^web."') do (
       echo rmdir %%D /s /q
    )
    

    If it's okay remove the echo in front of rmdir.

    The dir command just list directory names because of /AD and use a simple name output because of /B. To search on the beginning use findstr with /V. For negation use ^. Further the pipe symbol needs to be escaped ^|.


    If you want a dynamic batch script that uses arguments you can use the following, call it via batchname.bat "C:\foo" web. (if it's okay remove the echo in front of rmdir.):

    @echo off
    
    set INVARGS=0
    if [%1] == [] set "INVARGS=1"
    if [%2] == [] set "INVARGS=1"
    if %INVARGS% == 1 (
       echo echo %0 ^<directory^> ^<directory_prefix^>
       goto eof
    )
    
    set "folder=%1%"
    set "prefix=%2%"
    
    pushd "%folder%"
    echo List of folders that should be deleted:
    for /F "delims=" %%D in ('dir /B /AD ^| findstr /v "^%prefix%"') do (
       echo "%cd%\%%D"
    )
    popd
    
    :choice
    echo.
    set /P "c=Are you sure you want to continue [Y/N]?"
    if /I "%c%" EQU "Y" goto yes
    if /I "%c%" EQU "N" goto eof
    goto :choice
    
    :yes
    echo.
    pushd "%folder%"
    for /F "delims=" %%D in ('dir /B /AD ^| findstr /v "^%prefix%"') do (
       echo rmdir %%D /s /q
    )
    popd
    
    :eof