Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a for loop in windows command line?

I was wondering if this was possible? I'm not familiar with using windows command line, but I have to use it for a project I'm working on. I have a a number of files, for which I need to perform a function for each. I'm used to working with python, but obviously this is a bit different, so I was hoping for some help.

Basically I need the for loop to iterate through 17 files in a folder, perform a function on each (that's using the specific software I have here for the project) and then that will output a file with a unique name (the function normally requires me to state the output file name) I would suck it up and just do it by hand for each of the 17, but basically it's creating a database of a file, and then comparing it to each of the 17. It needs to be iterated through several hundred times though. Using a for loop could save me days of work.

Suggestions?

like image 631
TheFoxx Avatar asked Jun 25 '12 15:06

TheFoxx


People also ask

Can I use for loop in CMD?

FOR /F. 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.

How do you repeat a line in CMD?

Type R in the line command field of the line that is to be repeated. If you want to repeat the line more than once, type a number that is greater than 1 immediately after the R command. Press Enter.

Which command is used for looping?

There are several looping commands, such as WHILE… ENDWHILE, DO… LOOP, REPEAT… UNTIL, and FOR…

What does %% mean in CMD?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.


1 Answers

The commandline interpreter does indeed have a FOR construct that you can use from the command prompt or from within a batch file.

For your purpose, you probably want something like:

FOR %i IN (*.ext) DO my-function %i 

Which will result in the name of each file with extension *.ext in the current directory being passed to my-function (which could, for example, be another .bat file).

The (*.ext) part is the "filespec", and is pretty flexible with how you specify sets of files. For example, you could do:

FOR %i IN (C:\Some\Other\Dir\*.ext) DO my-function %i 

To perform an operation in a different directory.

There are scores of options for the filespec and FOR in general. See

HELP FOR 

from the command prompt for more information.

like image 146
Myk Willis Avatar answered Sep 28 '22 22:09

Myk Willis