批处理脚本 - 计算文件中字符的出现次数

3
使用Windows XP中的.bat文件,如何读取文本文件并查找其中字符实例的数量?
例如,我有一个包含以下内容的字符串:
""OIJEFJ"JOIEJKAJF"""LKAJFKLJEIJ""JKLFJALKJF"LKJLKFA""""LKJKLFJLKADJF

我希望它能计算文件中有多少个 " ,并返回数量。


人类如何解决这个问题?你能用一行代码或一个字符来解决它吗? - jeb
@jeb,您能否请再阐述一下问题? - Anthony Miller
现在我很困惑,我无法翻译你的评论,我的英语太差了 :-( - jeb
不确定,但也许@jeb的意思是询问您想要计算每个字符出现的次数还是每行中出现该字符的次数。我猜测应该是前者,但我希望得到确认,以确保无误。 - Andriy M
我想找到字符计数。在我的例子中,有13个“字符”。 - Anthony Miller
1个回答

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

现在介绍快速而简洁的方法:
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%

最后,统计文件中字符数的方法:

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

妈呀...我以前用过那个方法来单独筛选字符...真不敢相信我居然忘了。既然我更明白“慢”方法,我就用那个吧。 - Anthony Miller
删除字符并获取长度差异,非常聪明 :). 有人在这里创建了快速字符计数: https://dev59.com/xW025IYBdhLWcg3wtobX - Fantastory

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接