Batch Script - Count instances of a character in a file

痴心易碎 提交于 2020-02-02 11:37:05

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/7983925/batch-script-count-instances-of-a-character-in-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!