FOR-F - CMD


Overview

The FOR /F command in Windows CMD is used for parsing textual data or command output and generating a set of actions for each parsed item. This command is effective in processing structured text files, manipulating strings, and handling data piped from other commands or generated in scripts.

Syntax

The basic syntax for the FOR /F command is:

FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
FOR /F ["options"] %variable IN ('command') DO command [command-parameters]
  • “options”: Optional parameters that define the behavior of the command, such as how to parse each line of text or which lines to skip.
  • %variable: A variable that stores a portion of the parsed data for each iteration.
  • file-set: Specifies a file or set of files to read and parse.
  • “string”: Direct input text to parse.
  • ‘command’: A command whose output will be parsed.
  • command [command-parameters]: The command to execute for each item of the parsed data.

Options/Flags

  • eol=c: Specifies an end-of-line character (c) as a comment line marker.
  • skip=n: Skips the first n lines of the file.
  • delims=xxx: Specifies a delimiter set, where “xxx” are the delimiter characters.
  • tokens=x,y,m-n: Specifies which tokens from each line are to be passed to the FOR variable.
  • usebackq: Enables the use of the alternate quoting style in file-set, command, and strings.

Examples

Example 1: Basic Usage
Read lines from a file and display them:

FOR /F %i IN (myfile.txt) DO @echo %i

Example 2: Using Tokens and Delimiters
Parse each line of a CSV file, extracting the first and third columns:

FOR /F "tokens=1,3 delims=," %a IN (data.csv) DO @echo %a %b

Example 3: Process Command Output
List all directories in the current directory:

FOR /F "delims=" %i IN ('dir /b /ad') DO @echo %i

Common Issues

  • Variable Scope: Variables may not persist outside of the loop. Use SETLOCAL EnableDelayedExpansion and !variable! for accessing updated variable values within the loop.
  • Special Characters: Issues can arise if the input text contains special characters like & or <. Proper quoting or escaping is required.

Integration

Combine FOR /F with other commands to create powerful scripts:

Example: Deleting Temporary Files

FOR /F "delims=" %i IN ('dir /b *.tmp') DO del "%i"
  • FOR: General iteration command for looping through items.
  • IF: Conditional processing in scripts.
  • ECHO: Displaying messages or turning command echoing on or off.
  • SETLOCAL and ENDLOCAL: Controls the visibility of script changes to the environment.

Additional resources can be found in the Windows CMD documentation.