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.

  • /d

    Walks through folders instead of files.

  • /r [ruta]

    Walks through a folder tree recursively.

  • /l

    Counts numbers in the form (start,step,end).

  • /f

    Processes 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=N

    With /f, number of lines skipped at the start.

Usage examples

  • for %i in (*.txt) do echo %i

    Prints the name of each .txt file in the folder.

  • for /l %i in (1,1,5) do echo %i

    Counts from 1 to 5.

  • for /d %d in (*) do echo %d

    Lists the subfolders of the current folder.

  • for /f "tokens=1,2 delims=," %a in (datos.csv) do echo %a - %b

    Reads 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.

Related commands