欢迎访问yhm138的博客园博客, 你可以通过 [RSS] 的方式持续关注博客更新

MyAvatar

yhm138

HelloWorld!

写一个cmd脚本,列出指定目录下的所有子目录和文件,限制层数

在 Windows 的 CMD shell 中,tree 命令并不直接支持指定层数。

你可以编写CMD脚本达到相同目标。

# 要不还是用这个吧
tree /F

不打印出文件,只打印出目录

@echo off
setlocal
set "root=%~1"
set "maxdepth=%~2"
set "curdepth=0"
set "indent="

:loop
pushd "%root%"
for /d %%D in (*) do (
    echo %indent%+-- %%D
    if %curdepth% lss %maxdepth% (
        set /a "curdepth+=1"
        set "root=%%D"
        set "indent=%indent%    "
        call :loop
        set "indent=%indent:~,-4%"
        set /a "curdepth-=1"
    )
)
popd
exit /b
tree_depth.cmd C:\path\to\directory 2

不仅打印出目录,还打印出文件

@echo off
setlocal
set "root=%~1"
set "maxdepth=%~2"
set "curdepth=0"
set "indent="

:loop
pushd "%root%"
for /d %%D in (*) do (
    echo %indent%"+--" %%D
    if %curdepth% lss %maxdepth% (
        set /a "curdepth+=1"
        set "root=%%D"
        set "indent=%indent%    "
        call :loop
        set "indent=%indent:~,-4%"
        set /a "curdepth-=1"
    )
)

:: Loop for files
for %%F in (*) do (
    echo %indent%"|--" %%F
)

popd
exit /b
tree_depth.cmd C:\path\to\directory 2
posted @ 2023-09-17 11:37  yhm138  阅读(134)  评论(0编辑  收藏  举报