Bob
Bob

Reputation: 4970

.bat - how to remove "dot" and "dot dot" items from dir command

I'm writing a batch to run a command on all directories in current directory.

To start, I do dir /A:D but that gives even the . and .. directories on which I do NOT want to run my command.

I know I can exclude them by writing

IF NOT %%x EQU "."
    IF NOT %%x EQU ".."

But is there more generic way? Like:

set EXCLUDED=".","..","bob"
set FOLDERS=dir /A:D
rem for each in EXCLUDED, remove from FOLDERS
rem run my command(s) on FOLDERS

Upvotes: 0

Views: 2048

Answers (2)

Stephan
Stephan

Reputation: 56180

Obviously, you use a for loop (probably for /f "..." %%x in ('dir ...') do ...). There is a special parameter /D to work with directories:

@echo off
setlocal EnableDelayedExpansion
FOR /D %%x IN (*) do (
  ECHO %%x|FINDSTR /ivx "bob joe jane">nul && (
    ECHO do stuff with %%x
  ) || (
    ECHO skipping %%x
  )
)

(works, as long as there are no spaces in the "to exclude" folder names)

PS: no need to exclude . and .. here, because for /d doesn't show them.

Upvotes: 0

Thomas Weller
Thomas Weller

Reputation: 59258

You can add the /b switch to exclude . and .., as long as you don't need the other information given by dir /a:d.

To exclude other directories, use find /v like this:

dir /a:d /b | find /v "bob" | find /v "alice"

The /v switch will output everything else but the given line.

Upvotes: 4

Related Questions