如何遍历Windows批处理文件中的文件夹树/子树?

时间:2009-08-20 18:16:03

标签: windows batch-file

在Windows批处理文件中,有没有办法遍历文件夹/子文件夹层次结构,对每个文件执行某些操作?

4 个答案:

答案 0 :(得分:14)

是的,您可以使用带有for开关的/r命令执行此操作,例如:

for /r %%f in (*) do echo %%f

另请参阅this question示例。

答案 1 :(得分:4)

您可以将FOR命令与/r开关一起使用,该命令将遍历目录树,执行您在每个目录的DO语句中指定的任何内容。在那里,您可以使用FOR块中的dir /b *.*嵌套另一个SET语句。

答案 2 :(得分:1)

幸运的是,我对此线程的目的非常相似。我相信INSTRUCTION

dir /b /s /ad *.* [enter]

将生成DIRECTORY TREE

complete_path\dir_01_lev_01
complete_path\dir_02_lev_01
complete_path\dir_03_lev_01
complete_path\dir_01_lev_01\dir_11_lev_02
complete_path\dir_01_lev_01\dir_12_lev_02
complete_path\dir_02_lev_01\dir_13_lev_02
complete_path\dir_02_lev_01\dir_14_lev_02
complete_path\dir_02_lev_01\dir_15_lev_02
complete_path\dir_03_lev_01\dir_16_lev_02

但我想要结果如下

complete_path\dir_01_lev_01
complete_path\dir_01_lev_01\dir_11_lev_02
complete_path\dir_01_lev_01\dir_12_lev_02
complete_path\dir_02_lev_01
complete_path\dir_02_lev_01\dir_13_lev_02
complete_path\dir_02_lev_01\dir_14_lev_02
complete_path\dir_02_lev_01\dir_15_lev_02
complete_path\dir_03_lev_01
complete_path\dir_03_lev_01\dir_16_lev_02

所以,这篇SCRIPT是BORN:)

@echo off
rem
rem ::: My name is Tree-Folder-8-Level.cmd
rem
setlocal
rem ::: Put started PATH here
set i01=complete_path
for /f "delims=" %%a in ('dir "%i01%" /ad /on /b') do call :p001 "%%a"
endlocal
goto :eof

:p001
rem ::: Display 1st LEVEL of started PATH
echo %~1
for /f "delims=" %%b in ('dir "%i01%\%~1" /ad /on /b') do call :p002 "%~1\%%b"
goto :eof

:p002
rem ::: Display 2nd LEVEL of started PATH
echo %~1
for /f "delims=" %%c in ('dir "%i01%\%~1" /ad /on /b') do call :p003 "%~1\%%c"
goto :eof

:p003
rem ::: Display 3rd LEVEL of started PATH
echo %~1
for /f "delims=" %%d in ('dir "%i01%\%~1" /ad /on /b') do call :p004 "%~1\%%d"
goto :eof

:p004
rem ::: Display 4th LEVEL of started PATH
echo %~1
for /f "delims=" %%e in ('dir "%i01%\%~1" /ad /on /b') do call :p005 "%~1\%%e"
goto :eof

:p005
rem ::: Display 5th LEVEL of started PATH
echo %~1
for /f "delims=" %%f in ('dir "%i01%\%~1" /ad /on /b') do call :p006 "%~1\%%f"
goto :eof

:p006
rem ::: Display 6th LEVEL of started PATH
echo %~1
for /f "delims=" %%g in ('dir "%i01%\%~1" /ad /on /b') do call :p007 "%~1\%%g"
goto :eof

:p007
rem ::: Display 7th LEVEL of started PATH
rem :::     and 8th LEVEL of started PATH
echo %~1
for /f "delims=" %%h in ('dir "%i01%\%~1" /ad /on /b') do echo %~1\%%h
goto :eof

欢迎更明智的想法。 :)

答案 3 :(得分:-1)

dir /b /s /ad *.* | sort

无论路径深度如何,都应该给出相同的结果