Davida M
Davida M

Reputation: 25

counting chars in file name Windows batch

for example I have a foldet test and some files there: test1.txt, test12.txt, test123.txt ... i want a batch program to count characters in these filenames and output on the screen like - name "test1.txt" consists of 9 chars. name "test12.txt" consists of 10 chars. and so on.

i wrote this script but it does't work :(

   @echo off
    setlocal enableextensions enabledelayedexpansion
    set /p directory="specify Desirable Dir: "
    pushd "%directory%"
     for %%j in (*) do (
        set /a countch=0
          set OFileName=%%j
            :loop
            set NFileName=!OFileName:~0,%countch%!
            IF !OFileName!==!NFileName! (
                echo name "!OFileName!" consists of %countch% chars
            ) ELSE (
                set /a countch = countch + 1
                goto loop
            )    
    )
    popd
    endlocal
    pause

please help! thanks in advance ;)

Upvotes: 1

Views: 1876

Answers (2)

Magoo
Magoo

Reputation: 80013

@ECHO OFF
SETLOCAL 
SET "sourcedir=c:\sourcedir"
pushd "%sourcedir%"
for %%j in (*) do (
 set OFileName=%%j
 SETLOCAL ENABLEDELAYEDEXPANSION
 SET "ch="
 FOR /l %%L IN (2048,-1,0) DO IF NOT DEFINED ch (
  set ch=!OFileName:~%%L,1!
  IF DEFINED ch SET /a ch=1+%%L&echo name "!OFileName!" consists of !ch! chars
 )
 ENDLOCAL 
)
popd
GOTO :EOF

(though I changed the target directory for testing...)

Upvotes: 1

npocmaka
npocmaka

Reputation: 57252

here you can find a bunch of strlen implementations: http://ss64.org/viewtopic.php?id=424

:

  @echo off
    setlocal enableextensions enabledelayedexpansion
    set /p directory="specify Desirable Dir: "
    pushd "%directory%"
     for %%j in (*) do (

          set "OFileName=%%j"
          call :strlen0.3 OFileName fnamelen
          echo !fnamelen!
    )
    popd
    endlocal
    goto :eof

:strlen0.3  StrVar  [RtnVar]
  setlocal EnableDelayedExpansion
  set "s=#!%~1!"
  set "len=0"
  for %%A in (2187 729 243 81 27 9 3 1) do (
    set /A mod=2*%%A
    for %%Z in (!mod!) do (
        if "!s:~%%Z,1!" neq "" (
            set /a "len+=%%Z"
            set "s=!s:~%%Z!"

        ) else (
            if "!s:~%%A,1!" neq "" (
                set /a "len+=%%A"
                set "s=!s:~%%A!"
            )
        )
    )
  )
  endlocal & if "%~2" neq "" (set %~2=%len%) else echo **%len%**
exit /b
    pause

Upvotes: 1

Related Questions