Loop Through All Files In A Directory With DOS Batch

Tuesday, September 16, 2008 - 10:45

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.
1
2
3
4
5
directory\directory.html
directory\match.xls
directory\directory.xls
directory\file.txt
directory\file_back.txt
Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Comments

Hi..
How can we list only the files names, with its complete path.

Thanks

Amit, use /a as in the following:
1
dir /b /a-d-h-s > list.txt

Add new comment