batch-file

Batch file to count files matching first 6 characters in file name and output file group and its count


I would like to have a batch file to count all file names with common prefix and output the file group and its count. I have these files in a directory:

I want to group the first 3 by A11106*.zip and the last two by A11206*.zip.

My desired output is:

A11106: 3
A11206: 2

I have tried to copy sample codes from the forum, but they don't fulfilled my desired output.

Here is the code I have so far. But the output is not as described above.

@echo off
title Store Data Counter
:recurse
set I=1
echo "files counter"

FOR /f "tokens=*" %%A IN ('dir /a-d /b "Z:\StoreData\A11106*.zip"') do (call :showfiles "%%A")
echo A111: %I%

FOR /f "tokens=1" %%A IN ('dir /a-d /b "Z:\StoreData\A11206*.zip"') do (call :showfiles "%%A")
echo A112: %I%

pause
goto :eof

:showfiles
echo %1
set /a I+=1
goto :eof

Solution

  • Here is a batch code for this task.

    @echo off
    setlocal EnableExtensions DisableDelayedExpansion
    for /F "tokens=1 delims==" %%I in ('set Group# 2^>nul') do set "%%I="
    for %%I in ("*.zip") do set "FileName=%%~nI" & call :CountFile
    for /F "tokens=2,3 delims=#=" %%I in ('set Group# 2^>nul') do echo %%I: %%J
    endlocal
    exit /B
    :CountFile
    set "FileGroup=%FileName:~0,6%"
    set /A Group#%FileGroup%+=1
    goto :EOF
    

    "*.zip" can be extended with full path to the ZIP files to count.

    To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.

    And read also the Microsoft documentation about Using command redirection operators for an explanation of 2>nul used here to redirect the error message output by command SET from STDERR to device NUL to suppress it in case of no Group#* environment variable exists on starting the batch file or no *.zip file could be found in the current directory.

    The redirection operator > must be escaped here with ^ to be interpreted on executing command SET and not on parsing the FOR command line. Otherwise 2>nul without ^ would be interpreted as redirection for command FOR defined at an invalid position in the command line which would result in a batch execution exit because of a syntax error.

    Note: The simple code above does not work for all file names. For example, if there is the character % in the first six characters of the file name, the code does not work and an extended version of the code would be necessary to handle such file names too.