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.
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
Select columns from a text file
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 ‘>’.
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