简体   繁体   中英

Write a script to recursively list directories and files within it in Batch script

I am trying to write a batch script that recursively lists all directories and their files with *.js type in the below format:

For example, if I start with the C:\project directory

c:\project
project.js
project_time.js

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

I tried to implement the above logic in code as follows:

@echo off

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

pause

I was not able to print the directory under which the files are listed.

@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.

Here's an untested example, (I'm not expecting it to be quick if your base directory is large) :

@Echo Off
(
    For /F "Delims=" %%G In ('Dir /B /S /A:D "C:\Project" 2^> NUL') Do (
        %__AppDir__%where.exe /Q "%%G":*.js 1> NUL 2> NUL
        If Not ErrorLevel 1 (
            Echo/
            Echo %%G
            For /F "EOL=| Delims=" %%H In ('%__AppDir__%where.exe "%%G":*.js')Do (
                Echo %%~nxH
            )
        )
    )
) 1> "names.txt"
Pause

If you prefer to run something from the Command Prompt, then try this version:

(For /F "Delims=" %G In ('Dir /B/S/AD "C:\Project" 2^>NUL')Do @(%__AppDir__%where.exe /Q "%G":*.js >NUL 2>&1&&(Echo/&Echo %G&For /F "EOL=|Delims=" %H In ('%__AppDir__%where.exe "%G":*.js')Do @Echo %~nxH)))>"names.txt"

Two simple ways to do this:

dir /S *.js

You get the answers, just as you requested.

FORFILES /S /M *.js /C "cmd /c echo @path"

You get complete path for every file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM