Windows batch files: echo all files in a directory with a loop

13,171

Solution 1

If you look at the help you get when you run FOR /?, you'll see that you either want:

for /D %%Y in (%%~nX\*) do

or

for /F %%Y in ('dir /b %%~nX') do

Solution 2

Try this link -

http://rosettacode.org/wiki/Walk_a_directory/Recursively#Batch_File

Instead echo use copy.

Edit: Here you go

FOR /R <source-directory> %F IN (*.xml) DO COPY "%F" <destination-directory>

This will copy all *.xml files from source-directory to destination-directory recursively and flatten out the directory structure.

Share:
13,171
MxLDevs
Author by

MxLDevs

Updated on June 25, 2022

Comments

  • MxLDevs
    MxLDevs almost 2 years

    I have a program ABC that currently takes in one file and dumps out n number of files into a folder whose name is the same as the filename without the extension.

    The number of files created is arbitrary. I want to take all those output files and move them to another directory. This means when I pass in 10 files to program ABC, I will have the output all in one directory as opposed to 10 separate directories.

    I will use a nested for loop to accomplish this. The outer loop will send each argument to be processed by program ABC, and the inner loop will move each and all resulting files into my own folder of choice.

    I have the outer loop part finished, but am not sure how to retrieve the list of files in a folder.

    I first tried to echo them

    for /D %%Y in (dir %%~nX) do
      echo %%Y
    )
    

    where %%~nX is the name of the newly created folder from program ABC, but all it does is echo "dir" and the name of the folder rather than evaluate (dir %%~nX) before it tries to loop over it.

    Also, dir will include parent dir and current dir, which I do not want if I ever get it to work. How do I get rid of them, and is it possible to evaluate the command before looping over it?

  • MxLDevs
    MxLDevs about 13 years
    I used echo to verify that the files I am looking for are correct. But yes, I should've used /R or /F instead
  • MxLDevs
    MxLDevs about 13 years
    'dir /b %%~nX' syntax is what I was looking for. Thx.