Search code examples
batch-filecountfilenamesvariable-length

Echo x number of dots based on the length of the file name


I'm trying to find a way to echo x number of dots based on the length of the file name.

In the Batch-script I'm making, there is a part where it ECHO's the file name and size of a file.

The problem is that none of the file names do have the same amount of characters.

45545.ext.................8.23 MB
12341231.ext..............5.87 MB
543646767676.ext..........6.23 MB
34563456345634563.ext.....3.87 MB

Let's say I want 5 dots after the longest file name, then I need an X amount of dots after the shorter file names to get the the size of the files on the same line below each other, as shown above.

I've tried with a script I found on StackOverflow that counts the length of the file name. I'm not sure if I can use a "counter" to to this or not.

Thanks in advance! :)


Solution

  • You can use variable substrings with a for /l loop to determine the length of a string. Keep looping until x number of characters of filename is equal to filename, then you've found your length.

    Loop through all files in the directory to find the longest. Then add 5 to that to make sure the longest file still has 5 dots. Then for each file in the directory, that number minus length is the number of dots you need.

    Easy-peasy lemon squeezey.

    @echo off
    setlocal enabledelayedexpansion
    
    :: get longest filename in directory
    set longest=0
    for %%I in (*) do (
        call :length "%%~I" len
        if !len! gtr !longest! set longest=!len!
    )
    
    :: Dot fill each line
    for %%I in (*) do (
        call :length "%%~I" len
        set /a dots=%longest% + 5 - len
        <NUL set /P "=%%~I"
        call :dots !dots!
        echo %%~zI bytes
    )
    
    :: end main script
    goto :EOF
    
    :length <filename> <var_to_set>
    setlocal enabledelayedexpansion
    set "tmpfile=%~1"
    for /l %%I in (1,1,100) do (
        if "!tmpfile!"=="!tmpfile:~-%%I!" (
            endlocal && set "%~2=%%I"
            goto :EOF
        )
    )
    
    :dots <number_of_dots>
    setlocal
    for /l %%I in (1, 1, %~1) do <NUL set /P "=."
    goto :EOF
    

    Note: This script assumes you won't have any filenames longer than 100 characters. If you might, then increase the 100 in the for /l loop in the :length subroutine.

    If you want a speed-optimized :dots subroutine, replace the last four lines of the script with the following:

    :dots <number_of_dots>
    setlocal enabledelayedexpansion
    set "dots=...................................................................................................."
    <NUL set /P "=!dots:~-%1!"
    goto :EOF