Reputation: 49
I'm trying to loop over all sub-directories in a directory and echo its name to a text file, then for each file in each of these sub-directories echo the filename and extension to the same text file. So far I have the following in my .bat file:
@echo off
for /D %%d in (*) do (echo %%d >> test.txt
for /r %%i in (%%d) do echo %%~nxi >> test.txt)
Individually
for /D %%d in (*) do (echo %%d >> test.txt
and
for /r %%i in (*) do echo %%~nxi >> test.txt)
work to output the names of the sub-directories or files in *, but when I combine them I just get the names of the sub-directories repeated a bunch of times in the text file.
What am I doing wrong in this nested loop? How do I fix it to output what I need?
Example of required output:
Directory1
File1.txt
File2.txt
File3.txt
Directory2
Filex.jpg
Filey.jpg
Upvotes: 1
Views: 340
Reputation: 24466
If all you need is one level of depth, then don't use for /r
. That recurses. Instead, do this:
@echo off & setlocal
>test.txt (
for /d %%D in (*) do (
echo %%~D
for %%I in ("%%~D\*") do echo %%~nxI
)
)
Upvotes: 3