1

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
Iyashu5040
  • 49
  • 1
  • 7
  • 1
    Why not just use `tree`? – rojo Nov 15 '16 at 13:07
  • The ultimate aim of this is to generate code for me. The directory I'm working with has several folders, each with lots of images. I want to use the script to generate code to build an object containing all the files instead of having to capture all the information manually. – Iyashu5040 Nov 15 '16 at 13:11
  • Answered a similar question a few weeks ago. http://stackoverflow.com/a/40225913/1417694 – Squashman Nov 15 '16 at 13:23

1 Answers1

3

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
    )
)
rojo
  • 24,000
  • 5
  • 55
  • 101