Looping batch file windows

How do you loop in a Windows batch file?

What is the syntax for a FOR loop in a Windows batch file?

8 Answers 8

list is a list of any elements, separated by either spaces, commas or semicolons.

command can be any internal or external command, batch file or even — in OS/2 and NT — a list of commands

parameters contains the command line parameters for command. In this example, command will be executed once for every element in list, using parameters if specified.

A special type of parameter (or even command) is %%A, which will be substituted by each element from list consecutively.

If you want to do something x times, you can do this:

  • Start = 1
  • Increment per step = 1
  • End = 200

and you will get several pages of help text.

Conditionally perform a command several times.

syntax-FOR-Files-Rooted at Path

syntax-FOR-List of numbers

  • Take a set of data
  • Make a FOR Parameter %%G equal to some part of that data
  • Perform a command (optionally using the parameter as part of the command).
  • —> Repeat for each item of data

If you are using the FOR command at the command line rather than in a batch program, use just one percent sign: %G instead of %%G .

The first parameter has to be defined using a single character, for example the letter G.

In each iteration of a FOR loop, the IN ( . ) clause is evaluated and %%G set to a different value

If this clause results in a single value then %%G is set equal to that value and the command is performed.

If the clause results in a multiple values then extra parameters are implicitly defined to hold each. These are automatically assigned in alphabetical order %%H %%I %%J . (implicit parameter definition)

If the parameter refers to a file, then enhanced variable reference can be used to extract the filename/path/date/size.

You can of course pick any letter of the alphabet other than %%G . but it is a good choice because it does not conflict with any of the pathname format letters (a, d, f, n, p, s, t, x) and provides the longest run of non-conflicting letters for use as implicit parameters.

Windows batch file with loop through subfolders

I didnt succeed writing an approriate batch file and would appreciate some help.

Let’s say I have an exe in D:\Test\ called script.exe. To execute this script.exe it requires an additional argument of a .bin files (e.g. bin01.bin, bin02.bin).

Therefore it would be like: script.exe -i bin01.bin, script.exe -i bin01

I want the script to execute with all .bin files from all subfolders

Читайте также:  Как сменить пароль wifi windows 10

D:\Test\script.exe
D:\Test\Folder01\bin01.bin
D:\Test\Folder01\bin02.bin
D:\Test\Folder02\bin01.bin
D:\Test\Folder03\bin01.bin

anyone could help me here? Thanks a lot in advance.

1 Answer 1

For direct execution from within a command prompt window:

And the same command line for usage in a batch file:

The command FOR searches recursive in directory D:\Test and all subdirectories for files matching the wildcard pattern *.bin .

The name of each found file is assigned with full path to case-sensitive loop variable I .

FOR executes for each file the executable D:\Test\script.exe with first argument -i and second argument being the name of found file with full path enclosed in double quotes to work for any *.bin file name even those containing a space or one of these characters: &()[]<>^=;!’+,`

@ at beginning of entire FOR command line just tells Windows command interpreter cmd.exe not to echo the command line after preprocessing before execution to console window as by default.

@ at beginning of D:\Test\script.exe avoids the output of this command to console executed on each iteration of the loop.

Most often the echo of a command line before execution is turned off at beginning of the batch file with @echo off as it can be seen below.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

How to make for loop in windows batch file run in name order

I have a windows batch file that does this:

But the for loop goes through the files randomly (not in the name order), it first run s5.01, then s4.06, then s4.08, then s4.10, then s4.07. How can I make them run in the name order?

It used to work, but now it doesn’t. What may cause this problem?

3 Answers 3

Jerry’s answer might very well be what is causing the problem.

You might solve it by changing

for %%s in (*.sql) do call

for %%s in (dir»*.sql ^| sort) do call

Edit cudo’s to LonelyPixel

The posted solution does not work as is on a Windows 8 machine (perhaps it did back then with Windows XP but I have no idea).

Following is a working solution using Windows 8 command prompt.

If memory serves, it will operate on the files in the order they’re returned by the file system. As such, if you run it on a disk partition that’s formatted with NTFS, the names will be returned in sorted order so they’ll be processed in sorted order. If the disk partition is formatted with something like FAT or FAT32, the names will be retrieved (and processed) in a more or less random order.

I too had to deal with spaces in the filenames, so I added quotes around the input variable like so:

In my case it was SQLCMD, with the scripts in a subdirectory, like so:

How do you loop through each line in a text file using a windows batch file?

I would like to know how to loop through each line in a text file using a Windows batch file and process each line of text in succession.

Читайте также:  Для windows phone dmss для

12 Answers 12

I needed to process the entire line as a whole. Here is what I found to work.

The tokens keyword with an asterisk (*) will pull all text for the entire line. If you don’t put in the asterisk it will only pull the first word on the line. I assume it has to do with spaces.

If there are spaces in your file path, you need to use usebackq . For example.

From the Windows command line reference:

To parse a file, ignoring commented lines, type:

This command parses each line in Myfile.txt, ignoring lines that begin with a semicolon and passing the second and third token from each line to the FOR body (tokens are delimited by commas or spaces). The body of the FOR statement references %i to get the second token, %j to get the third token, and %k to get all of the remaining tokens.

If the file names that you supply contain spaces, use quotation marks around the text (for example, «File Name»). To use quotation marks, you must use usebackq. Otherwise, the quotation marks are interpreted as defining a literal string to parse.

By the way, you can find the command-line help file on most Windows systems at:

In a Batch File you MUST use %% instead of % : (Type help for )

What this does: The «do call :process %%i %%j %%k» at the end of the for command passes the information acquired in the for command from myfile.txt to the «process» ‘subroutine’.

When you’re using the for command in a batch program, you need to use double % signs for the variables.

The following lines pass those variables from the for command to the process ‘sub routine’ and allow you to process this information.

I have some pretty advanced uses of this exact setup that I would be willing to share if further examples are needed. Add in your EOL or Delims as needed of course.

Improving the first «FOR /F..» answer: What I had to do was to call execute every script listed in MyList.txt, so it worked for me:

—OR, if you wish to do it over the multiple line:

Edit: The example given above is for executing FOR loop from command-prompt; from a batch-script, an extra % needs to be added, as shown below:

@MrKraus’s answer is instructive. Further, let me add that if you want to load a file located in the same directory as the batch file, prefix the file name with %

dp0. Here is an example:

NB:: If your file name or directory (e.g. myfile.txt in the above example) has a space (e.g. ‘my file.txt’ or ‘c:\Program Files’), use:

, with the type keyword calling the type program, which displays the contents of a text file. If you don’t want to suffer the overhead of calling the type command you should change the directory to the text file’s directory. Note that type is still required for file names with spaces.

Читайте также:  Когда придет время установки windows 10

I hope this helps someone!

dp0** before the for loop. This would make sure you are referencing a file in the directory the batch file is in. Thanks for the observation – Marvin Thobejane Jul 18 ’13 at 12:01

The accepted answer is good, but has two limitations.
It drops empty lines and lines beginning with ;

To read lines of any content, you need the delayed expansion toggling technic.

Findstr is used to prefix each line with the line number and a colon, so empty lines aren’t empty anymore.

DelayedExpansion needs to be disabled, when accessing the %%a parameter, else exclamation marks ! and carets ^ will be lost, as they have special meanings in that mode.

But to remove the line number from the line, the delayed expansion needs to be enabled.
set «var=!var:*:=!» removes all up to the first colon (using delims=: would remove also all colons at the beginning of a line, not only the one from findstr).
The endlocal disables the delayed expansion again for the next line.

The only limitation is now the line length limit of

8191, but there seems no way to overcome this.

How to make for loop in windows batch file run in name order

I have a windows batch file that does this:

But the for loop goes through the files randomly (not in the name order), it first run s5.01, then s4.06, then s4.08, then s4.10, then s4.07. How can I make them run in the name order?

It used to work, but now it doesn’t. What may cause this problem?

3 Answers 3

Jerry’s answer might very well be what is causing the problem.

You might solve it by changing

for %%s in (*.sql) do call

for %%s in (dir»*.sql ^| sort) do call

Edit cudo’s to LonelyPixel

The posted solution does not work as is on a Windows 8 machine (perhaps it did back then with Windows XP but I have no idea).

Following is a working solution using Windows 8 command prompt.

If memory serves, it will operate on the files in the order they’re returned by the file system. As such, if you run it on a disk partition that’s formatted with NTFS, the names will be returned in sorted order so they’ll be processed in sorted order. If the disk partition is formatted with something like FAT or FAT32, the names will be retrieved (and processed) in a more or less random order.

I too had to deal with spaces in the filenames, so I added quotes around the input variable like so:

In my case it was SQLCMD, with the scripts in a subdirectory, like so:

Оцените статью