3

Using a batch script (.bat file) in windows xp, how would I go about reading a text file and finding how many instances of a character exists?

For example, I have a string with the following:

""OIJEFJ"JOIEJKAJF"""LKAJFKLJEIJ""JKLFJALKJF"LKJLKFA""""LKJKLFJLKADJF

I want it to count how many " there are in the file and return the count.

Andriy M
  • 76,112
  • 17
  • 94
  • 154
Anthony Miller
  • 15,101
  • 28
  • 69
  • 98
  • And how a human would solve it? Do you can solve it for one line, or one single character? – jeb Nov 02 '11 at 17:00
  • @jeb can you please reiterate the question(s)? – Anthony Miller Nov 02 '11 at 19:47
  • Now I am confused, I can't translate your comment, my English is too poor :-( – jeb Nov 02 '11 at 20:23
  • Not sure but maybe @jeb meant to ask whether you wanted to count every character found or every line where the character occurred. I rather guess it's the former, but I would like it to be confirmed, just to be sure. – Andriy M Nov 02 '11 at 21:06
  • I want to find the character count. In the case of my example, there are 13 " characters. – Anthony Miller Nov 03 '11 at 14:04

1 Answers1

8

Let's start counting the characters in a line. First the slow and clear method:

set i=-1
set n=0
:nextChar
    set /A i+=1
    set c=!theLine:~%i%,1!
    if "!c!" == "" goto endLine
    if !c! == !theChar! set /A n+=1
    goto nextChar
:endLine
echo %n% chars found

Now the fast and cryptic method:

call :strLen "!theLine!"
set totalChars=%errorlevel%
set strippedLine=!theLine:%theChar%=!
call :strLen "!strippedLine!"
set /A n=totalChars-%errorlevel%
echo %n% chars found
goto :eof

:strLen
echo "%~1"> StrLen
for %%a in (StrLen) do set /A StrLen=%%~Za-4
exit /B %strLen%

Finally the method to count the characters in a file:

set result=0
for /F "delims=" %%a in ('findstr "!theChar!" TheFile.txt') do (
    set "theLine=%%a"
    place the fast and cryptic method here
    set /A result+=n
)
echo %result% chars found
Aacini
  • 65,180
  • 12
  • 72
  • 108
  • man... i've used that method to single out characters before... can't believe I forgot it. Since I understand the "Slow" method better, I'll be using that. – Anthony Miller Nov 03 '11 at 14:28
  • Remove chars and get length difference, supper smart :). Someone created fast character counting here: http://stackoverflow.com/questions/5837418/how-do-you-get-the-string-length-in-a-batch-file – Fantastory Dec 31 '14 at 13:07