How to do something to each file in a directory with a batch script

WindowsFileLoopsBatch FileCmd

Windows Problem Overview


How do you iterate over each file in a directory with a .bat or .cmd file?

For simplicity please provide an answer that just echoes the filename or file path.

Windows Solutions


Solution 1 - Windows

Command line usage:

for /f %f in ('dir /b c:\') do echo %f

Batch file usage:

for /f %%f in ('dir /b c:\') do echo %%f

Update: if the directory contains files with space in the names, you need to change the delimiter the for /f command is using. for example, you can use the pipe char.

for /f "delims=|" %%f in ('dir /b c:\') do echo %%f

Update 2: (quick one year and a half after the original answer :-)) If the directory name itself has a space in the name, you can use the usebackq option on the for:

for /f "usebackq delims=|" %%f in (`dir /b "c:\program files"`) do echo %%f

And if you need to use output redirection or command piping, use the escape char (^):

for /f "usebackq delims=|" %%f in (`dir /b "c:\program files" ^| findstr /i microsoft`) do echo %%f

Solution 2 - Windows

Alternatively, use:

forfiles /s /m *.png /c "cmd /c echo @path"

The forfiles command is available in Windows Vista and up.

Solution 3 - Windows

Easiest method:

From Command Line, use:

for %f in (*.*) do echo %f

From a Batch File (double up the % percent signs):

for %%f in (*.*) do echo %%f

From a Batch File with folder specified as 1st parameter:

for %%f in (%1\*.*) do echo %%f

Solution 4 - Windows

Use

for /r path %%var in (*.*) do some_command %%var

with:

  • path being the starting path.
  • %%var being some identifier.
  • *.* being a filemask OR the contents of a variable.
  • some_command being the command to execute with the path and var concatenated as parameters.

Solution 5 - Windows

Another way:

for %f in (*.mp4) do call ffmpeg -i "%~f" -vcodec copy -acodec copy "%~nf.avi"

Solution 6 - Windows

I had some malware that marked all files in a directory as hidden/system/readonly. If anyone else finds themselves in this situation, cd into the directory and run for /f "delims=|" %f in ('forfiles') do attrib -s -h -r %f.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrian R. BondyView Question on Stackoverflow
Solution 1 - WindowsFranci PenovView Answer on Stackoverflow
Solution 2 - WindowsPaul HouxView Answer on Stackoverflow
Solution 3 - WindowsGordon BellView Answer on Stackoverflow
Solution 4 - WindowsmstroblView Answer on Stackoverflow
Solution 5 - WindowsthistleknotView Answer on Stackoverflow
Solution 6 - WindowsAnonView Answer on Stackoverflow