How to remove all folders named "Sample" from directory and subfolders?

276 views Asked by At

I'm looking for a command line that I can add to a batch that I use.

Here's what I need to be able to do:

Lets say I have a directory:
C:\Users\username\Videos

With a subdirectories

C:\Users\username\Videos\test\sample
C:\Users\username\Videos\test2\sample

What command would I need to use to delete the sample folders in both subdirectories but not the test/test2 folders?

If you know of a way to use RMDIR that would be great but if not I'm open to ideas.

2

There are 2 answers

0
MC ND On BEST ANSWER

The command

dir /b /s /ad "C:\Users\username\Videos\sample"

will generate the list of folders to delete. Now, to process this list we wrap the command in a for /f command that will perform the directory removal command for each line in the output of the previous command

@echo off
    setlocal enableextensions disabledelayedexpansion

    for /f "delims=" %%a in ('
        dir /b /s /ad "C:\Users\username\Videos\sample"
    ') do rd /s /q "%%a"

Or, to use it from command line

for /f "delims=" %a in ('dir /b /s /ad "C:\Users\username\Videos\sample"') do rd /s /q "%a"

In both cases, the for /f will iterate over the output lines of the dir command, storing the line in its replaceable parameter %a and executing the code after the do clause.

The default behaviour of for command is to tokenize the input lines splitting them using spaces and tabs as delimiters. To disable this behaviour delims= clause is used: with no delimiters there is only one token containing the full line.

0
Jerry Jeremiah On

What about:

for /f %i in ('dir /b/s/ad ^| findstr -I "\Sample$"') do rmdir %i

That does a recursive directory listing and filters for Sample directorues and then takes the list and deletes each one. If you are going to put it in a batch file you need to double every % like this:

for /f %%i in ('dir /b/s/ad ^| findstr -I "\Sample$"') do rmdir %%i