How to find subdirectories of only two levels deep

2019-09-08 17:10发布

I got a script that lists all subdirectories in a folder and put them in a file:

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

effect looks like this:

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

what I really need:

\\test\e$\1\target1
\\test\e$\1\target2
\\test\e$\1\target3
\\test\e$\2\target1
\\test\e$\2\target2

even better (if possible) in this form (separator: "|:"):

\\test\e$\1\target1|:\\test\e$\1\target2|:\\test\e$\1\target3|:\\test\e$\2\target1|:\\test\e$\2\target2

1条回答
够拽才男人
2楼-- · 2019-09-08 17:58
@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

You would need to change the setting of sourcedir to suit your circumstances.

May have problems with directorynames containing characters that have a special meaning to cmd.

查看更多
登录 后发表回答