PredictableBeaco
PredictableBeaco

Reputation: 97

What is %f in the for loop command?

From this example right here. https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/for#additional-references

for %f in (*.doc *.txt) do type %f

In the preceding example, each file that has the .doc or .txt extension in the current directory is substituted for the %f variable until the contents of every file are displayed. To use this command in a batch file, replace every occurrence of %f with %%f. Otherwise, the variable is ignored and an error message is displayed.

Are these different from variables in this example?

https://www.tutorialspoint.com/batch_script/batch_script_variables.htm

set message=Hello World 
echo %message%

What are these called? How do I manipulate them?

Upvotes: 3

Views: 25888

Answers (1)

npocmaka
npocmaka

Reputation: 57272

in batch scripting slang it is called for loop token and the example above will work only in the command prompt. For a batch file you'll need double %.

These tokens changes their values on each iteration of the for loop. Example (this can be executed in the command prompt):

for %a in (1 2) do @echo %a

this will have two iterations - in the first the value if the %%a token it will be 1 and on the seconds 2.

You can use for loops to read files (with /f switch and no quotes) ,to iterate files (with no switch) or directories (with /d switch), iterate through strings (again without switch but using wild cards in strings is not possible) to read files (with /f and no quotes), or process a string (again with /f).

you can also split the value of each iteration with "delims" option and then you'll need more consecutive letters :

for /f "tokens=1,2 delims=-" %a in ("1-2-3") do @echo %a:%b

this will split the string in the quotes by - and will take the first and the second part accessible by the %a and %b tokens.

More on for loops:

https://ss64.com/nt/for.html

https://ss64.com/nt/for2.html

https://ss64.com/nt/for_r.html

https://ss64.com/nt/for_d.html

https://ss64.com/nt/for_f.html

https://ss64.com/nt/for_cmd.html

Upvotes: 7

Related Questions