0

considering with my scripts below, I want to count the number of characters inside the file. First, I want to count the lines and store it. Second given counted lines, I am now going to count for the number of characters. The process should be, the number of characters will be deducted with the number of lines counted. The problem is that when I use my scripts, the commands will no longer work, I don't if I am wrong with my scripts specially the use of SETLOCAL

cls
@echo off

set ctr=0
set str=

setlocal enabledelayedexpansion
FOR /f "tokens=*" %%G IN (file.txt) DO (call :count "%%G")
GOTO :eof

:count
set /a ctr+=1
goto :eof


setlocal enabledelayedexpansion 
for /f "tokens=* delims=" %%i in (file.txt) do (set str=!str! %%i)

call :len "%str%" a

setlocal enabledelayedexpansion
set /a a-=ctr
echo The string has %a% characters.
endlocal
goto :eof


:len <string> <length_variable>

setlocal enabledelayedexpansion 
set l=0
set str=%~1

:len_loop
set x=!str:~%l%,1!
if not defined x (
endlocal
set "%~2=%l%"
goto :eof)
set /a l=%l%+1
goto :len_loop
Matt Williamson
  • 6,947
  • 1
  • 23
  • 36
  • You don't have to use the setlocal enabledelayedexpansion like you are doing. You only need it at the top and in any functions where you have IF / For blocks of code where you are setting variables inside of them. – Matt Williamson Feb 25 '15 at 15:39

1 Answers1

0

I'm sorry if I'm misunderstanding the point of your question, but there are much easier ways to get a character count of your files.

for %%I in ("filename.txt") do echo %%~zI

would do it. Getting a line count is a simple one-liner as well.

type "filename.txt" | find /v /c ""

You're employing the Rube Goldberg method of character counts, and it's going to give you incorrect results anyway if your file contains blank lines. If you're looking for help with your :len subroutine, here's a more efficient alternative based on jeb's :StringLength routine:

:length <return_var> <string>
setlocal enabledelayedexpansion
set "tmpstr=%~2"
set ret=0
for %%I in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
    if not "!tmpstr:~%%I,1!"=="" (
        set /a ret += %%I
        set "tmpstr=!tmpstr:~%%I!"
    )
)
endlocal & set "%~1=%ret%"
goto :EOF

Does this help?

Community
  • 1
  • 1
rojo
  • 24,000
  • 5
  • 55
  • 101