【问题标题】:Batch Script - Count instances of a character in a file批处理脚本 - 计算文件中字符的实例
【发布时间】:2011-12-20 12:00:25
【问题描述】:

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

例如,我有一个字符串如下:

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

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

【问题讨论】:

  • 人类将如何解决它?你能解决一行,还是一个字符?
  • @jeb 你能重复一下问题吗?
  • 现在我很困惑,我无法翻译你的评论,我的英语太差了:-(
  • 不确定,但也许@jeb 的意思是问您是否要计算找到的每个字符或出现该字符的每一行。我宁愿猜是前者,但我希望它得到证实,只是为了确定。
  • 我想查找字符数。在我的示例中,有 13 个 " 字符。

标签: windows-xp count batch-file


【解决方案1】:

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

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

【讨论】:

  • 人...我以前用这种方法来挑选字符...不敢相信我忘记了。由于我更了解“慢”方法,因此我将使用它。
  • 删除字符并获得长度差异,超级聪明:)。有人在这里创建了快速字符计数:stackoverflow.com/questions/5837418/…
猜你喜欢
  • 2017-11-14
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 2018-02-18
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多