Search notes:

cmd.exe: for /f %%X in ('command') do command

In a for /f loop, a command that can be executed can be put within single quotes. In such a case, the for /f loop iterates over the lines produced by the quoted command.

Basic behaviour

The following simple and not very useful example iterates over the lines that are produced by dir and echos each line's first word:
@for /f %%a in ('dir') do @echo %%a
Github repository about-cmd.exe, path: /commands/for/f/command/dir.bat

Filtering the output of a command

It might be more useful if the output is filtered with find and then the fourth token (that is the directory name) is echoed.
Note that special characters such as the pipe or ampersand need to be escaped with the caret:
@for /f "tokens=4" %%a in ('dir ^| find "<DIR>"') do @echo %%a
Github repository about-cmd.exe, path: /commands/for/f/command/dir-find.bat
This example, of course, is for demonstration purposes only, the canonical way to display directories is dir /od

usebackq

With the special option usebackq, the command is not placed within single quotes but rather within backquotes:
@for /f "tokens=4 usebackq" %%a in (`dir ^| find "<DIR>"`) do @echo %%a
Github repository about-cmd.exe, path: /commands/for/f/command/dir-find-usebackq.bat

Index