首页 > 解决方案 > 编写脚本以在批处理脚本中递归列出其中的目录和文件

问题描述

我正在尝试编写一个批处理脚本,该脚本以以下格式递归列出所有目录及其文件:*.js

例如,如果我从C:\project目录开始

c:\project
project.js
project_time.js

c:\project\core
core.js
core_render.js
core_application.js

我尝试在代码中实现上述逻辑,如下所示:

@echo off

for /r %%f in (*.js) do (
  echo %%f >> names.txt
)

pause

我无法打印列出文件的目录。

标签: windowsbatch-filecmd

解决方案


@echo off
setlocal disabledelayedexpansion

set "lastdir="

(   for /r %%A in (*.js) do (
        set "nextdir=%%~dpA"

        setlocal enabledelayedexpansion
        if /i not "!lastdir!" == "!nextdir!" (

            rem Empty line and directory path.
            if defined lastdir @echo(
            @echo !nextdir!
        )
        endlocal

        rem Filename.
        @echo %%~nxA

        set "lastdir=%%~dpA"
    )
) > "names.txt"

The lastdir variable is to record the last directory path so it is echoed only once.

If lastdir is different to %%~dpA:

  • If lastdir is defined, then an empty line will be echoed.
  • Directory path of found file is echoed.

Filename is always echoed.

for modifiers dp is the drive and path. nx is the name and extension.

setlocal enabledelayedexpansion is used only where needed so paths with ! are not vulnerable.

I am not going to suggest a command line solution as it would be very long. Instead suggest use of tree command if the output format is suitable.


推荐阅读