在for循环中排除文件夹匹配字符串?

问题描述 投票:0回答:2

给出一个这样的for循环:

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

有没有办法排除某些文件夹? 如果文件夹的名称是foobar,请不要回显任何内容。 但如果它包含foo并且除了foobar之外什么都不要回声

windows batch-file cmd
2个回答
1
投票

您将不得不使用for /f循环来处理更复杂的命令:

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

另外一个选项:

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

1
投票

PowerShell可用于选择目录并排除特定名称。

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
)

并举例说明。

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
© www.soinside.com 2019 - 2024. All rights reserved.