Iterate all files in a directory using a 'for' loop Iterate all files in a directory using a 'for' loop windows windows

Iterate all files in a directory using a 'for' loop


This lists all the files (and only the files) in the current directory:

for /r %i in (*) do echo %i

Also if you run that command in a batch file you need to double the % signs.

for /r %%i in (*) do echo %%i

(thanks @agnul)


Iterate through...

  • ...files in current dir: for %f in (.\*) do @echo %f
  • ...subdirs in current dir: for /D %s in (.\*) do @echo %s
  • ...files in current and all subdirs: for /R %f in (.\*) do @echo %f
  • ...subdirs in current and all subdirs: for /R /D %s in (.\*) do @echo %s

Unfortunately I did not find any way to iterate over files and subdirs at the same time.

Just use cygwin with its bash for much more functionality.

Apart from this: Did you notice, that the buildin help of MS Windows is a great resource for descriptions of cmd's command line syntax?

Also have a look here: http://technet.microsoft.com/en-us/library/bb490890.aspx


To iterate over each file a for loop will work:

for %%f in (directory\path\*) do ( something_here )

In my case I also wanted the file content, name, etc.

This lead to a few issues and I thought my use case might help. Here is a loop that reads info from each '.txt' file in a directory and allows you do do something with it (setx for instance).

@ECHO OFFsetlocal enabledelayedexpansionfor %%f in (directory\path\*.txt) do (  set /p val=<%%f  echo "fullname: %%f"  echo "name: %%~nf"  echo "contents: !val!")

*Limitation: val<=%%f will only get the first line of the file.