批处理脚本 - 计算文件中字符的实例 [英] Batch Script - Count instances of a character in a file

查看:195
本文介绍了批处理脚本 - 计算文件中字符的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

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

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

这篇关于批处理脚本 - 计算文件中字符的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆