for
Windows CMD · Terminal · reference only
What it does
Repeats a command for each element of a set: files, folders, numbers or lines of a file.
Syntax
for [/d | /r | /l | /f] %variable in (conjunto) do orden
Options and parameters
%i in (conjunto)Walks through the set's elements; in a .bat it is written %%i.
/dWalks through folders instead of files.
/r [ruta]Walks through a folder tree recursively.
/lCounts numbers in the form (start,step,end).
/fProcesses the lines of a file or a command's output, splitting them into fields.
tokens=With /f, which fields of each line are used, such as tokens=1,2.
delims=With /f, characters that separate the fields.
skip=NWith /f, number of lines skipped at the start.
Usage examples
for %i in (*.txt) do echo %iPrints the name of each .txt file in the folder.
for /l %i in (1,1,5) do echo %iCounts from 1 to 5.
for /d %d in (*) do echo %dLists the subfolders of the current folder.
for /f "tokens=1,2 delims=," %a in (datos.csv) do echo %a - %bReads a CSV and shows its first two columns.
Notes and common mistakes
- In the console you type %i with a single percent sign; inside a .bat file you must write %%i.
- Before using for with del or rd, test with echo to see which elements would be processed.