0

I would like to make a batch file to list only the first file from every directories in a tree with hundreds of sub-directories and output the results in a text file.

So far I found a way to do it in a single directory but it does not work within a tree.

for /f "delims=" %%F in ('dir /b /o-n') do set file=%%F
echo %file% >>filelist.txt

I tried adding /s to dir but it only list the first file of the last directory.

aschipfl
  • 33,626
  • 12
  • 54
  • 99
johnnyg0
  • 13
  • 3

1 Answers1

0

If you want filenames with paths then:

@(For /F Delims^= %%G In ('Dir /B/S/AD/ON')Do @Set "}=?"&For /F "EOL=? Delims=" %%H In ('Dir "%%G" /B/A-D/ON 2^>NUL')Do @If Defined } Echo %%G\%%H&Set "}=")>"filelist.txt"

If you wanted the filenames only then similarly:

@(For /F Delims^= %%G In ('Dir /B/S/AD/ON')Do @Set "}=?"&For /F "EOL=? Delims=" %%H In ('Dir "%%G" /B/A-D/ON 2^>NUL')Do @If Defined } Echo %%H&Set "}=")>"filelist.txt

However, please be aware that the above method will still enumerate each directory after it has output the first file in each, so if there are many files in one or more of those it may not be the most efficient of methods.

In that case, it may be more efficient to Call a label instead:

@(For /F Delims^= %%G In ('Dir /B/S/AD/ON')Do @Call:Sub "%%G")>"filelist.txt"
@GoTo :EOF
:Sub
@For /F "EOL=? Delims=" %%G In ('Dir %1 /B/A-D/ON 2^>NUL')Do @Echo "%~1\%%G"&Exit /B
@Echo ;"%~1"&Exit /B

The above example is designed to also print the directories containing no child files, prefixed with a semicolon. If you don't want those, then just remove Echo ;"%~1"& from the last line. Also if you don't want the full paths, just remove %~1\ from the penultimate line.


If you wanted to output to the file on each iteration, instead of writing all of the output at the end only, (according to your comment below), then the following is an adaption of the first example, to show you how to do that:

@For /F Delims^= %%G In ('Dir /B/S/AD/ON')Do @Set "}=?"&For /F "EOL=? Delims=" %%H In ('Dir "%%G" /B/A-D/ON 2^>NUL')Do @If Defined } Echo "%%G\%%H">>"filelist.txt"&Set "}="
Compo
  • 36,585
  • 5
  • 27
  • 39
  • This is great! I tried it in a folder with ~100000 files and it took less than 2 minutes and it worked perfectly. I wish I could upvote you but my reputation isn't high enough, but I will call you a wizard instead :) Do you think it would be possible to output the results as they are found instead of being written at the end of the process? (the output file is empty until the process is completed). – johnnyg0 Aug 24 '21 at 01:45
  • I just marked it. Thank you very much again. I've been looking for a way to do this for so long before asking here. I really appreciate your help. – johnnyg0 Aug 25 '21 at 00:00