FOR /F – Windows CMD Command

Loop command: against the results of another command.

FOR /F processing of a command consists of reading the output from the command one line at a time and then breaking the line up into individual items of data or ‘tokens’. The DO command is then executed with the parameter(s) set to the token(s) found.

The FOR command is the answer to innumerable questions where you want to take the output of some command, store it in a variable (%%G) then do something with the result

To select that one line of output, you can search for the text “loss” (which is always present), then use the Tokens parameter to select the number of lost packets, here this is 0 but it will vary each time you run the command.

The tricky part is always splitting up the line of interest into the right tokens, in this case, I’m splitting on the characters ‘=’ and ‘(‘
these two characters split the line into 5 chunks of text and we pull out the fourth one with “tokens=4”

By default, /F breaks up the command output at each blank space, and any blank lines are skipped.
You can override this default parsing behavior by specifying the “options” parameter. The options must be contained within “quotes”

It is possible to use the syntax on this page to parse a text file with TYPE (‘Type somefile.txt’) but you will get much better performance using FOR /F File contents (somefile.txt) as that will save loading TYPE.EXE.

The precedence/priority of FOR command options is: usebackq > skip > delims > eol > tokens

usebackq

This option is useful when dealing with a command that already contains one or more straight quotes.
The backquote character is just below the ESC key on most keyboards. See the FOR /F page for other effects of usebackq.

Usebackq can be abbreviated to useback (undocumented.)

eol

The default end-of-line character is a semicolon ';' when the FOR command reads a text file (or even a character string), any line that STARTS with the eol character will be ignored. In other words,

it is treated as a comment. Use eol=X to change the eol character to X. Often you will want to turn this feature off so that every line of your data file is processed, in theory, "eol=" should turn this feature off, but in practice,

this fails to work correctly - it will set eol to whatever the next character is, often the quote or space character. One workaround is to set eol to some unusual character that you don’t expect to ever encounter in the data file e.g. "eol=€" or "eol=¬". Another method is to escape every delimiter For /f tokens^=*^ delims^=^ eol^= %%a in (file.txt) do... (see forum for a discussion of this)

Delims

More than one delimiter can be specified so a string like 'abcd+efg+hijk;lmno;pqr' can be broken up using "delims=;+".

for /f "tokens=1,2,3,4,5 delims=;+" %%G in ('type filename.txt') do echo %%G %%H %%K

You can use almost any character as a delimiter, but they are case sensitive. If you don’t specify delims it will default to "delims=" delims should always the last item in the options string "tokens=3 delims= " not "delims=  tokens=3" This is because the quotations around the options string do double duty as a terminator for the delims character(s), which is particularly important when that character is a space. You can remove all delimiters by using "delims=" this will place everything on the line into the first token. One special case is using a quote (") as a

delimiter. By default this will be seen as the end of the "delims string" unless all the outer enclosing quotes are removed and all delimiter chars are instead escaped with ^. for /f tokens^=1^,2^,3^ delims^=^" %%G in ('type filename.txt') do echo %%G %%H %%I n.b. some text editors will enter the TAB character as a series of sp

The following ASCII characters can be used as FOR tokens: ASCII 63 - 93 inclusive, 31 tokens: ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ASCII 95-123 inclusive, 29 tokens: _ a b c d e f g h i j k l m n o p q r s t u v w x y z { (there are a few other characters that can be used, but require escaping)

A single FOR /F command can never parse more than 31 tokens, to use more requires a workaround with multiple FOR commands.

The numbers specified in tokens= are automatically sorted, so for example tokens=5,7,1-3 and tokens=1,2,3,5,7 both produce the same result.

Matching the same token more than once (tokens=1,2,1) can give unpredictable results. Token variables can of course be used multiple times: Echo %%G %%H %%G FOR tokens variables (or parameter names) are global, so in complex scripts which call one FOR statement from within another FOR statement you can refer to both sets of parameters.

A single FOR /F command can never parse more than 31 tokens, to use more requires a workaround with multiple FOR commands.

The numbers specified in tokens= are automatically sorted, so for example tokens=5,7,1-3 and tokens=1,2,3,5,7 both produce the same result.

Matching the same token more than once (tokens=1,2,1) can give unpredictable results. Token variables can of course be used multiple times: Echo %%G %%H %%G

FOR tokens variables (or parameter names) are global, so in complex scripts which call one FOR statement from within another FOR statement, you can refer to both sets of parameters.

command

This can be almost any internal or external command.

A common pattern is to set a variable = some token output to make it available for later processing/display. When doing this be sure to read the section Using variables within a FOR loop on the main FOR page.

Also, consider the case where the command fails, the FOR command will trap the error, but the DO clause is never reached – this means the variable will not be changed. This can cause subtle bugs. When using the FOR command in a batch file always use SETLOCAL at the start to localize all variables. Alternatively, you can explicitly clear the variable(s) to remove any existing value, just before running the FOR loop.

command_to_process

The command_to_process can be almost any internal or external command, but there are a few commands that have no effect when are called through FOR /F – SHIFT, SETLOCAL, ENDLOCAL, CALL: Subroutine.
To be clear these can be used as part of the command, but not command_to_process

We use DIR /S (even if the folder has no subfolders) to make DIR return the full path to each file.
In the example above the long filename has to be surrounded in “quotes” and those quotes have to be escaped using ^

Although the above is a trivial example, being able to set a variable equal to each long filename, in turn, allows much more complex processing to be done.

More examples can be found on the Syntax / Batch Files pages and the other FOR pages below.

FOR does not, by itself, set or clear the Errorlevel.
FOR is an internal command.

You may also like...

1 Response

  1. LarryLog says:

    this contact form

Leave a Reply

Your email address will not be published.