zhzoo
zhzoo

Reputation: 65

Exclude folder matching string within for loop?

Given a for loop such as this:

FOR /d /r "topDir" %%G in (*foo*) DO (
    echo %%G
)

is there a way to exclude certain folders?
Specifically do not echo anything if the folder's name is foobar.
But do echo if it contains foo and is anything but foobar

Upvotes: 0

Views: 1702

Answers (2)

npocmaka
npocmaka

Reputation: 57252

You'll have to use for /f loop to process a more complex command:

set "topDir=c:\topDir"
for /f "tokens=* delims=" %%a in (' dir /s /a:d "%topDir%\*foo*"^| find /v "foobar"') do (
   echo %%a
)

another option:

FOR /d /r "topDir" %%G in (*foo*) DO (
    echo %%G | find /v "foobar" 1>nul 2>nul && (
        echo %%G
    ) 
)

Upvotes: 1

lit
lit

Reputation: 16236

PowerShell can be used to select directories and exclude specific names.

C:>TYPE t.bat
@echo off
DIR /A:D
FOR /F "usebackq tokens=*" %%d IN (`powershell.exe -NoProfile -Command "Get-ChildItem -Directory -Recurse -Filter '*foo*' -Exclude 'foobar' | ForEach-Object { $_.Name }"`) DO (
    ECHO Selected directory is %%d
)

And an example execution.

C:>CALL t.bat
 Volume in drive C has no label.
 Volume Serial Number is 0E33-300C

 Directory of C:\src\t\f

2017-12-31  16:46    <DIR>          .
2017-12-31  16:46    <DIR>          ..
2017-12-31  16:12    <DIR>          barfoo
2017-12-31  16:12    <DIR>          barfoochow
2017-12-31  16:12    <DIR>          foo
2017-12-31  16:12    <DIR>          foobar
2017-12-31  16:39    <DIR>          zzz
               0 File(s)              0 bytes
               7 Dir(s)  792,276,733,952 bytes free
Selected directory is barfoo
Selected directory is barfoochow
Selected directory is foo

Upvotes: 1

Related Questions