Link Search Menu Expand Document

Windows Command Line for Loop

For Loop, a control flow statement used for iteration of any object facilitates the repeated code execution. In layman’s language, Loop refers to an efficient and easy way to execute something repeatedly, say ten times, without performing the codes individually. A loop carries out a repetition of codes, but it can be of various types: for, do, while statements, etc.

A “For Loop” function repeats the object until the value of the object equals zero. The benefit of using a for loop function is that we are aware of the exact times the Loop will execute before it initiates. This statement is available in most programming languages, and they vary in types such as traditional for loops, vectorized for loops, iterator based for loops, and compound for loops.

A popular user interface today adopted by programmers is Windows Command-Line. Instead of using a mouse, the Windows Command Line is navigated by typing commands at prompts. Windows Command Line comprises an interpreter with a FOR construct that one may use from either the prompt or within a batch file. In windows, the For Loop feature can be used in many ways. Its simplest form is:

for %i in (set) do command command-arguments

Here, the list of variants for which the command must be run is referred to as an asset. For Loop's full options can be viewed using ‘for /? ‘. Loop can be used in many ways depending on the user’s requirements. The different methods are as follows:

1.   Command For Selective Files

In case you want to run a command for each specific file in the directory, For command can be used as follows:

for /F %i in (‘command to get files list) do command %i

2.   Command for deleting excess users

Users might have a list of login names to be deleted from the system. Say, the login names are user23, user24, user25, user26, and user27. The names can be deleted from the system in a single step by using For Loop instead of deleting them one by one. The required command would be as follows:

for %i in (user23 user24 user25 user26 user27) do net user /delete %i

If this list is stored in a file, say ABC, then the following command may be used:

for /F %i in (ABC) do net user /delete %i

3.   Command for Filtering Columns from File

In case of unwanted columns present in a text file comprising of multiple columns, filtering them is easy with the following command:

Say the file has five columns. Now, to print columns 1 and 5, the command would be:

for /F "tokens=1,5" %i in (test.txt) do @echo %i %j

In the case of commas, users can either retain or separate them using simple commands. The output can be redirected to a new file using the Operator Pipe.

Other useful articles:


Back to top

© , CMD Windows — All Rights Reserved - Terms of Use - Privacy Policy