Loop Through All Files In A Directory With DOS Batch
Note: This post is over two years old and so the information contained here might be out of date. If you do spot something please leave a comment and we will endeavour to correct.
16th September 2008 - 4 minutes read time
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.
type file.txt
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.
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.
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.
Comments
Submitted by Amit Gandhi on Thu, 06/05/2014 - 08:56
Permalinkdir /b /a-d-h-s > list.txt
Submitted by Ray on Sun, 08/03/2014 - 15:45
PermalinkAdd new comment