defect122

Windows batch - counting files with a batch using for loops

Feb 16th, 2012
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Batch – Programming .
  2.  
  3. Scenario: Counting Files and adding them to logfiles
  4.  
  5. How to count files in a directory and how to put them in logfiles.
  6.  
  7. Sometimes it is helpful to know how many files and what files you have saved in a directory. You could count them manually or use a tool of some sort, but it is also realizable with a batch file. A batch for this under Windows NT could look somehting like the following:
  8.  
  9. @echo off
  10. Break off
  11.  
  12. REM ======= Part 1 ========
  13.  
  14. echo First part of this batch (Listing and counting files in G:\Documents)
  15. echo.
  16. set dir="G:\Documents\"
  17. set log="G:\Logfiles-documents\log-txt-file.txt"
  18. set log2="G:\Logfiles-documents\log-file-count.txt"
  19. echo Put files (txt) into %log%
  20. for /R %dir% %%f in (*.txt*) do (
  21.     dir "%%f" /b/s/a-d/w/OD/OS >> %log%
  22. )
  23. for /R %dir% %%f in (*.txt*) do (
  24.     echo Numbers of .txt files in %dir%: >> %log2%
  25.     dir "%%f" /b/s/a-d |find /v /c "::" >> %log2%
  26. )
  27. set log3="G:\Logfiles-documents\log-doc-odt-file.txt"
  28. echo Put files (odt/doc) into %log3%
  29. for /R %dir% %%f in (*.doc *.odt) do (
  30.     dir "%%f" /b/s/a-d/w/OD/OS >> %log3%
  31.    
  32. )
  33. for /R %dir% %%f in (*.odt *.doc) do (
  34.     echo Numbers of .odt-files in %dir%: > %log2%
  35.     dir G:\Documents\*.odt /b/s/a-d |find /v /c "::" > %log2%
  36.     echo Numbers of .doc-files in %dir%: > %log2%
  37.     dir G:\Documents\*.doc /b/s/a-d |find /v /c "::" > %log2%
  38. )
  39. echo Show all subdirectories of %dir%
  40. dir %dir% /a:d/s > G:\Logfiles-documents\count-directories.txt
  41. dir %dir% /a:d
  42. pause >nul
  43.  
  44. What this batch code does?
  45. The batch counts all *.txt files and puts their number in one logfile. The name of every *.txt file is saved in another logfile. It also counts all .odt and .doc files and lists them in another logfile.  And then last it lists all subdirectories of G:\Documents and puts them in a logfile.
  46.  
  47.  
  48. Notes for this batch:
  49.  
  50. Make sure to use dir "%%f" and not just %%f.
  51. Use for /R to include all subdirectories.
  52. >> adds the information to the logfile instead of creating a new one. You can also use >.
  53. But I prefer the >> notation.
  54. The structure of this code can vary. The notation above is just an example but I think this is the most convenient way to write a batch like this.
  55. The counting of these files like the odt and doc files can of course be applied to every sort of filetype. So the batch is just a general example of how to count files and create logs.
Advertisement
Add Comment
Please, Sign In to add comment