- Batch to loop through all files with predefined list or set of extensions and ignore all other file types
- 1 Answer 1
- How do you loop in a Windows batch file?
- 8 Answers 8
- How do you loop through each line in a text file using a windows batch file?
- 12 Answers 12
- How to loop through files matching wildcard in batch file
- 7 Answers 7
- Loop Through All Files In A Directory With DOS Batch
- Comments
- Add new comment
- Related Content
- Syncing Files Using The Windows Command Line
- Set An IP Address From The Command Prompt In Windows
Batch to loop through all files with predefined list or set of extensions and ignore all other file types
I have following windows-batch script to loop through all files in the current directory:
I know I can loop through a specific file type by using *.ext , but I need to loop through all the given below file types and ignore all other types, that also in single FOR loop only:
How can I achieve that by doing slightest modifications to my code as possible ?
I am not much of a batch-scripter, so any help would be much appreciated.
1 Answer 1
What about using this command line in your batch file?
Or perhaps better depending on what you want to do:
The version with DIR works also for files with hidden attribute set and is better when files in current directory are renamed, moved or deleted, i.e. the current directory files list changes due to the commands in the body of FOR loop because of list of files processed by FOR does not change once DIR command is executed which is not the case on using first solution. The first solution can easily result in an unexpected behavior like double processing a file, skipping unexpected files or an endless running loop when files are renamed, moved, modified or deleted in current directory.
Run in a command prompt window for /? and dir /? for help on those two commands which support both specifying multiple wildcard patterns on arguments list.
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.
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.
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.
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 loop through files matching wildcard in batch file
I have a set of base filenames, for each name ‘f’ there are exactly two files, ‘f.in’ and ‘f.out’. I want to write a batch file (in Windows XP) which goes through all the filenames, for each one it should:
- Display the base name ‘f’
- Perform an action on ‘f.in’
- Perform another action on ‘f.out’
I don’t have any way to list the set of base filenames, other than to search for *.in (or *.out) for example.
7 Answers 7
Assuming you have two programs that process the two files, process_in.exe and process_out.exe:
nf is a substitution modifier, that expands %f to a file name only. See other modifiers in https://technet.microsoft.com/en-us/library/bb490909.aspx (midway down the page) or just in the next answer.
nf later? – Colonel Panic Mar 6 ’15 at 10:10
modifiers to do things, like in my example, just get the filename. It’s just habit for me to use that in case the * does the full path or something. There are a handful of these modifiers (midway down the page): microsoft.com/resources/documentation/windows/xp/all/proddocs/… – Jim Buck Mar 7 ’15 at 19:20
You can use this line to print the contents of your desktop:
Once you have the %%I variable it’s easy to perform a command on it (just replace the word echo with your program)
In addition, substitution of FOR variable references has been enhanced You can now use the following optional syntax:
In the above examples %I and PATH can be replaced by other valid values. The %
syntax is terminated by a valid FOR variable name. Picking upper case variable names like %I makes it more readable and avoids confusion with the modifiers, which are not case sensitive.
You can get the full documentation by typing FOR /?
Easiest way, as I see it, is to use a for loop that calls a second batch file for processing, passing that second file the base name.
According to the for /? help, basename can be extracted using the nifty
n option. So, the base script would read:
Then, in process.cmd, assume that %0 contains the base name and act accordingly. For example:
There might be a better way to do this in one script, but I’ve always been a bit hazy on how to pull of multiple commands in a single for loop in a batch file.
EDIT: That’s fantastic! I had somehow missed the page in the docs that showed that you could do multi-line blocks in a FOR loop. I am going to go have to go back and rewrite some batch files now.
Loop Through All Files In A Directory With DOS Batch
DOS Batch is the Windows equivalent of shell scripting and can be used to perform all sorts of different actions. Anything that you type into a DOS prompt on a Windows machine can be used in a bat file to quickly do something that you would otherwise have to repeat many times over. To create a bat file just make a file and give it the extension «bat». If you run a DOS prompt and navigate to the directory that the bat file exists in you can type the name of the file to get it to do certain actions. If you called your file «action.bat» you can run it by typing «action» or «action.bat». Starting with a simple example, if you want to print the contents of a file to screen then you need the type command, followed by the file.
However, this puts a lot of rubbish on the screen. If you wanted to create a backup of that file then you would write the following.
type file.txt > file_back.txt
This takes the contents of one file and puts it in another. To loop through every file in a directory you need to use the following line.
FOR %%i IN (*.*) DO echo %%i
This code will loop through the contents of a directory and print out each file name to screen. This will also list the bat file that you put in the directory so another solution might be to run the bat file from the directory above and use the following code.
FOR %%i IN (directory\*.*) DO echo %%i
The following snippet of code takes the previous example and does something useful. It loops through the directory and puts every file name that it finds into a file called list.txt.
FOR %%i IN (directory\*.*) DO echo %%i >> list.txt
The >> symbol will append any content to the file, so for every iteration of the loop the list.txt file gets one line bigger, until all of the files have been listed. In an example directory the following would be seen in the list.txt file.
Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK. Phil is currently a Developer at Code Enigma.
Comments
Amit Gandhi (Thu, 06/05/2014 — 08:56)
Ray (Sun, 08/03/2014 — 15:45)
Add new comment
Related Content
Syncing Files Using The Windows Command Line
To sync files using the Windows command line you will need to use the xcopy command. The default action of this program is to copy a file or directory from one place to another, but you can give it flags to tell it to sync the files. There are a few flags available (use xcopy /? to see them all) but you will probably only want to use the following:
Set An IP Address From The Command Prompt In Windows
Rather than use the old connection properties dialog in Windows you can open up a command prompt and use the netsh to set up all sorts of network specific settings. The most useful part of this is that you can create a bat file that will allow you to quickly change your local IP address very quickly.
To see a list of the network connections available you can use the following command.