For is loop command in Windows. Using this command we can simplify some of the repetitive tasks. The usage of this command is explained below with examples.
The simplest form of for command is:
for %i in (set) do command command-arguments
Here set means the list of variants for which the command needs to be run. I’m not listing the for loop’s full options here as same can be found by running the command ‘for /? ‘. Instead I have explained below with examples as to how to use for loop in different use cases.
Example 1: Delete user accounts in bulk
You have a list of login names whose accounts need to be deleted from the system. Let’s say the user names are user1, user2, user3, user4, user5, user6. To delete all these user accounts with a single command we can run the below command.
for %i in (user1 user2 user3 user4 user5 user6) do net user /delete %i
If the list of user accounts is stored in a file then we can delete the accounts using the below command.
for /F %i in (filename) do net user /delete %i
Similarly, we can add new user accounts in batch using for command.
Example 2: Select columns from a text file (Similar to linux ‘cut’ command)
If you have a text file with multiple columns, and if you want to filter out certain unwanted columns from the file, you can do it using for command easily.
Let’s say my file has 4 columns separated with space as below.
abcd efgh ijkl mnop qrst uvwx yz1 adef efsa erafa afaf affaf ....
Now to print only the columns 2 and 4, I can use the below command.
for /F "tokens=2,4" %i in (test.txt) do @echo %i %j
You can redirect the output from the above command to a new text file using the operator pipe(‘|’)
If the file is separated with with comma(‘,’), as in CSV files, we can use the below command.
for /F "tokens=2,4 delims=," %i in (test.txt) do @echo %i %j
If you want to retain the comma(,) between the columns, you can add it as below.
for /F "tokens=2,4 delims=," %i in (test.txt) do @echo %i,%j
Example 3: Run a command on a list of files(Like linux ‘find -exec’ command)
You want to run an application/command on selective files in a directory. You can use for command for this use case as below.
for /F %i in ('command to get files list') do command %i
For example, you want to open all the log files using notepad application.
for /F %i in ('dir /b *.log') do notepad %i
dir /b *.log retrieves the list of all log files. For command iterates over the list and then opens them in notepad.