Search code examples
windowsbatch-filecmd

Windows Batch Loop Recursively to find all files with given name


I'm trying my best at writing a windows batch. I want to list all files with given name "ivy.xml" in a directory and all its subdirectories. Example:

  • Releases
    • Program01
      • 1.0.0
        • ivy.xml
      • 2.0.0
        • ivy.xml
    • Program02
      • 1.0.0
        • ivy.xml
      • 2.0.0
        • ivy.xml

So the output should be:

  • "Releases/Program01/1.0.0/ivy.xml"
  • "Releases/Program01/2.0.0/ivy.xml"
  • "Releases/Program02/1.0.0/ivy.xml"
  • "Releases/Program02/2.0.0/ivy.xml"

Code:

for /R "Releases" %%f in (ivy.xml) do echo "%%f"

But what I get is this:

  • "Releases\ivy.xml"
  • "Releases\Program02\ivy.xml"
  • "Releases\Program02\1.0.0\ivy.xml"
  • "Releases\Program02\2.0.0\ivy.xml"
  • "Releases\Program01\ivy.xml"
  • "Releases\Program01\1.0.0\ivy.xml"
  • "Releases\Program01\2.0.0\ivy.xml"

Solution

  • The for /R loop just iterates through the whole directory tree when there is no wildcard (?, *) to match against, so extend it by if exist to return existing items only:

    for /R "Releases" %%f in (ivy.xml) do if exist "%%f" echo "%%f"
    

    If there might be sub-directories called ivy.xml too you could exclude them by this:

    for /R "Releases" %%f in (ivy.xml) do if exist "%%f" if not exist "%%f\*" echo "%%f"
    

    Given that there is no file matching the pattern ivy.xml?, you could also just do this:

    for /R "Releases" %%f in (ivy.xml?) do echo "%%f"
    

    Another option is the dir command, given that there is no directory called ivy.xml in the root directory Releases, whose contents would then become returned instead:

    dir /S /B /A:-D "Releases\ivy.xml"
    

    Yet another option is to use the where command (the PATHEXT variable is cleared in the current session in order not to return files like ivy.xml.exe, for instance):

    set "PATHEXT="
    where /R "Releases" "ivy.xml"