简体   繁体   中英

How to recursively list all files of desired file type in a specified directory?

I want list all .java files in the desired directory using .bat script in Windows. When I run this:

set JMETALHOME=%cd%
dir %JMETALHOME%\jmetal\problems /S /B 

it lists all the files in the problems directory. But when I want to filter the files only to the java files:

set JMETALHOME=%cd%
dir %JMETALHOME%\jmetal\problems /S /B *.java > sources.txt

it lists all the .java files in the %JMETALHOME% folder.

There are two common methods to get names of all files with a specific file extension found in a directory tree recursively with full path. One common method is using command DIR and the other common method is using command FOR .

Example code demonstrating both methods for *.java and *.html files:

@echo off
set "JMETALHOME=%CD%"

dir "%JMETALHOME%\jmetal\problems\*.java" "%JMETALHOME%\jmetal\problems\*.html" /B /S >SourcesDir.txt

if exist SourcesFor1.txt del SourcesFor1.txt
for /R "%JMETALHOME%\jmetal\problems" %%I in (*.java *.html) do echo %%I>>SourcesFor1.txt

(for /R "%JMETALHOME%\jmetal\problems" %%I in (*.java *.html) do echo %%I)>SourcesFor2.txt

DIR requires the specification of 1 or even more wildcard patterns together with path (absolute or relative).

FOR offers the possibility to specify the path separately from the wildcard patterns.

FOR outputs the found file names line by line which requires either usage of >> redirection operator with an extra deletion of a perhaps already existing output file before running FOR as demonstrated above with SourcesFor1.txt example, or embedding FOR itself in a block and use > to redirect everything output by the block into a file overwriting a perhaps already existing file as demonstrated with SourcesFor2.txt example.

On second FOR example make sure not having a space between echo %%I and closing parenthesis ) of the block because otherwise this space would be appended on each file name written into output file SourcesFor2.txt .

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • del /?
  • dir /?
  • echo /?
  • for /?
  • if /?
  • set /?

Read also the Microsoft article about Using command redirection operators .

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