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

17
在Windows的批处理文件中,是否有一种方法可以遍历文件夹/子文件夹层次结构,在每个文件上执行某些操作?
5个回答

14

是的,你可以使用带有/r开关的for命令来实现这一点,例如:

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

参见此问题的示例。


这将遍历每个文件和目录。问题仅针对目录。使用 /d 仅获取第一级目录。使用 /r /d 进行递归操作。 - Peter

4
你可以使用带有 /r 开关的 FOR 命令,它会遍历目录树,在每个目录上执行你在 DO 语句中指定的操作。在那里,你可以嵌套另一个 FOR 语句,在 SET 块中使用 dir /b *.*

1

很幸运,我对这个主题有相似的目的。我认为INSTRUCTION(指令)

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

将会生成目录树作为结果。
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

所以,这个脚本诞生了 :)
@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

欢迎提出更好的想法。 :)


0

如果你想查询某个位置的文件夹并遍历它们,那么你应该首先将查询结果写入文本文件,然后遍历文件内容的行。以下示例展示了如何查找名称包含“dev”的一级子文件夹并遍历它们:

if exist FolderList.txt (
 del FolderList.txt
)
set query=dev
set /a count=0
pushd %yourLocation%
dir /ad /o-d /b *%query%* >> FolderList.txt
for /f "tokens=*" %%a in ('type FolderList.txt') do (
 set /a count+=1
 echo %count%."%%a"

)
popd 

Some sample results could be:
1.Adev
2.bDevc
3.devaa

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接