Reputation: 1078
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.
Upvotes: 2
Views: 196
Reputation: 5372
@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
:
lastdir
is defined, then an empty line will be 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.
Upvotes: 2
Reputation: 17493
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.
Upvotes: 0
Reputation: 38604
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"
Upvotes: 0