为什么批处理文件中的FOR循环显示与通配符模式不匹配的目录?

时间:2016-07-27 17:04:50

标签: batch-file for-loop

此批处理文件:

setlocal EnableDelayedExpansion
echo off
for %%a in (a b c d e f g h i j k l m n o p q r s t u v w x y z) do (
    for /D %%f in (K:\cases\%%a*) do (
          echo Found directory starting with-%%a directory=%%~nxf
    )
)

结果:

Found directory starting with-b directory=070441_0001_LAW
Found directory starting with-d directory=DELETE_012216_0118
Found directory starting with-e directory=eh_TEST_20151009
Found directory starting with-f directory=029947_0030_LAW
Found directory starting with-f directory=FB_Testing_Case
Found directory starting with-k directory=070441_0001_LAWPROD
Found directory starting with-l directory=060662_0012_LAW
Found directory starting with-l directory=LAW_68_Update
Found directory starting with-m directory=064451_0014_LAW
Found directory starting with-m directory=064451_0015_LAW
Found directory starting with-o directory=063113_0028_LAWPROD
Found directory starting with-o directory=072920_0001_LAWEDA
Found directory starting with-p directory=064451_1000_007_LAWPROD
Found directory starting with-q directory=063113_0028_LAWEDA
Found directory starting with-t directory=072920_0001_LAWPROD
Found directory starting with-t directory=064451_1000_005_LAWPROD
Found directory starting with-t directory=064451_1000_006_LAWPROD
Found directory starting with-t directory=TEST_06222016
Found directory starting with-u directory=060662_0012_LAWPROD

为什么显示的目录不以适当的字母开头?

1 个答案:

答案 0 :(得分:0)

在使用通配符模式搜索文件或目录时,低级Windows内核例程不仅会考虑长文件/目录名,还会考虑简短的8.3文件/目录名。

这会产生意想不到的结果。虽然长文件/目录名称与模式不匹配,但是由于短文件/目录名称与通配符模式匹配而避免误报的一种方法是额外检查模式的长名称,例如使用 FINDSTR < /强>

在没有 FINDSTR 的情况下,可以非常轻松地对这种情况进行额外检查,因为必须只验证长目录名是否真正以期望的字母不区分大小写开头。

@echo off
setlocal EnableExtensions EnableDelayedExpansion
for %%a in (a b c d e f g h i j k l m n o p q r s t u v w x y z) do (
    for /D %%D in (K:\cases\%%a*) do (
        set "DirectoryName=%%~nxD"
        if /I "!DirectoryName:~0,1!" == "%%a" (
            echo Found directory starting with %%a - directory=%%~nxD
        )
    )
)
endlocal

dir /AD /X可用于查看目录的短名称。

要了解使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并完全阅读为每个命令显示的所有帮助页面。

  • dir /?
  • echo /?
  • endlocal /?
  • for /?
  • if /?
  • set /?
  • setlocal /?