Software >> OS >> Windows >> Command Line >> FOR >> How to use for to loop through and process each line of output from a command or batch script

For lines containing spaces and to process each as a single variable use

for /F "tokens=*" %d in ('dir /a:d /b') do somecommand "%d"

e.g. you have subdirectories with spaces and below them *.txt files that you want to search for some KEYWORD

for /F "tokens=*" %d in ('dir /a:d /b') do findstr KEYWORD "%d/*.txt"

 

For lines containing delimiters and to process specific tokens from each line

for /F %a "tokens=1,2 delims=-" in ('dir /a:d /b') do somecommand %a %b

e.g. the directories are named like YYYY-MM-DD and you want to extract only YYY & MM from them

for /F %a "tokens=1,2 delims=-" in ('dir /a:d /b') do somecommand %a %b