如何找到只有两层深的子目录?

How to find subdirectories of only two levels deep?

我得到了一个列出文件夹中所有子目录并将它们放入文件中的脚本:

dir "\test\e$" /a:d /s /b | sort>"C:\folders.txt

效果是这样的:

\test\e$
\test\e$\target1
\test\e$\target1\in
\test\e$\target1\out
\test\e$\target2
\test\e$\target2\in
\test\e$\target2\out
\test\e$\target3
\test\e$\target3\in
\test\e$\target3\out
\test\e$
\test\e$\target1
\test\e$\target1\in
\test\e$\target1\out
\test\e$\target2
\test\e$\target2\in
\test\e$\target2\out
\test\e$\random_folder_without_in_subfolder

我真正需要的是:

\test\e$\target1
\test\e$\target2
\test\e$\target3
\test\e$\target1
\test\e$\target2

这种形式更好(如果可能)(分隔符:“|:”):

\test\e$\target1|:\test\e$\target2|:\test\e$\target3|:\test\e$\target1|:\test\e$\target2
@ECHO OFF
SETLOCAL
SET "sourcedir=."
FOR /f "delims=" %%a IN ('dir /s /b /ad "%sourcedir%" '
  ) DO (
 FOR /f "tokens=3,4delims=\" %%d IN ("%%a") DO IF "%%e"=="" (ECHO(%%a) ELSE GOTO secondway
)

:secondway
@ECHO off
SETLOCAL enabledelayedexpansion 
SET "sourcedir=."
SET "longline="
FOR /f "delims=" %%a IN ('dir /s /b /ad "%sourcedir%" '
  ) DO (
 FOR /f "tokens=3,4delims=\" %%d IN ("%%a") DO IF "%%e"=="" (
  SET "longline=!longline!|:%%a"
 ) ELSE GOTO done2
)

:done2
SET "longline=!longline:~2!"
SET longline
FOR /f "tokens=1*delims==" %%a IN ('set longline') DO ECHO %%b
GOTO :EOF

您需要更改 sourcedir 的设置以适合您的情况。

包含对 cmd 具有特殊含义的字符的目录名可能会出现问题。