批处理脚本 - 计算文件中字符的实例

Mec*_*ash 2 windows-xp batch-file count

在windows xp中使用批处理脚本(.bat文件),我将如何阅读文本文件并查找存在多少个字符实例?

例如,我有一个包含以下内容的字符串:

""OIJEFJ"JOIEJKAJF"""LKAJFKLJEIJ""JKLFJALKJF"LKJLKFA""""LKJKLFJLKADJF
Run Code Online (Sandbox Code Playgroud)

我希望它计算"文件中有多少并返回计数.

Aac*_*ini 8

让我们开始计算一行中的字符.首先是缓慢而清晰的方法:

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
Run Code Online (Sandbox Code Playgroud)

现在快速而神秘的方法:

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%
Run Code Online (Sandbox Code Playgroud)

最后计算文件中字符的方法:

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
Run Code Online (Sandbox Code Playgroud)