Learn how to use
for command to iterate over a list of items and run commands on each of them. We can run a command for each file in a directory, for example.
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 /? ‘. I have explained below with examples as to how to use for loop in different use cases.
Run command for each file
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.
Run command for each user
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 in a single step 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.
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