Search code examples
batch-filecommand-linefindfindstr

Find occurrences of a string in files and display "filename - count" through batch file


Batch file to search every single subfolder and every single file inside a directory and count the number of times a particular string is present in each file.

Would be useful if output is "filename - count".

Can do find /c "Microsoft" *.txt This works if all the files are in one folder.

How do you make the find loop through all the subfolders and each of its files and display the same result.

Findstr has /s which does that, doesnt work on find.


Solution

  • From command line:

    for /F "delims=" %G in ('findstr /I /S /M "Microsoft" "%CD%\*.txt"') do @find /I /C "Microsoft" "%~G" | findstr /V /R "^$"
    

    From a batch script:

    set "_srch=Microsoft"
    for /F "delims=" %%G in ('
           findstr /I /S /M "%_srch%" "%CD%\*.txt"') do (
        find /I /C "%_srch%" "%%~G" | findstr /V /R "^$"
    )
    

    Omitting the %CD%\ you will get relative paths.

    To get rid of ---------- from find output (command line):

    for /F "delims=" %G in ('findstr /I /S /M "Microsoft" "%CD%\*.txt"') do @for /F "tokens=1,*" %H in ('find /I /C "Microsoft" "%~G"') do @echo %I
    

    Resources: type for /?, find /?, findstr /?, set /? or go to An A-Z Index of the Windows CMD command line.