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.
Join Stack Overflow to learn, share knowledge, and build your career.
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.
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
/f needed after the for? According to the help docs, the /f flag opens and reads each file. Is that needed to echo or rename files?
– Snekse
Jun 25 '12 at 2:33
/f after FOR restricts it to files. Similarly, /d restricts to directories (folders) and /r instructs it to be recursive.
– user1582361
Aug 7 '12 at 15:15
'dir /b "c:\program files"' it should be `dir /b "c:\program files"`
– endavid
Aug 8 '16 at 13:24
Alternatively, use:
forfiles /s /m *.png /c "cmd /c echo @path"
The forfiles command is available in Windows Vista and up.
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
dir /B output with for.
– syneticon-dj
Jan 22 '14 at 15:55
Use
for /r path %%var in (*.*) do some_command %%var
with:
%%var was unexpected at this time. Can you give an exact example? I tried a bunch of variations of for /r . %%var in (*.*) do echo %%var
– hippietrail
Nov 20 '12 at 13:22
Another way:
for %f in (*.mp4) do call ffmpeg -i "%~f" -vcodec copy -acodec copy "%~nf.avi"
"%~nf" stands for name of the file without extension, where f is the name of the variable specified in for part. Docs: docs.microsoft.com/en-us/previous-versions/windows/it-pro/…
– Slava
Apr 27 '18 at 17:03
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.