我的批处理脚本错误地计算了文件中字符串的出现 [英] My batch script bad counting occurrences of string in a file
本文介绍了我的批处理脚本错误地计算了文件中字符串的出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
@echo off
set /a count = 0
for /f "delims=" %%a in ('dir "%~1" /a:-d /b') do call :next "%%a" "%~2"
echo found %count% occurances of "%~2"
pause
GOTO:EOF
:next
set num=
for /f "delims=" %%b in ('find /c %2 ^< %1') do set num=%%b
set /a count=count+num
我的代码对参数中指定的文本计数错误.有什么问题?
My code is wrong count of the text specified in the parameter. What's the problem?
推荐答案
正如Mark所说, Find
返回文件中匹配的行的数量,而不是数量一行中的单个字符串.为此,您需要使用另一种方法,例如:
As Mark said, find
return the number of lines that match in a file, not the number of individual strings in one line. To do so, you need to use another method, for example:
@echo off
setlocal EnableDelayedExpansion
set /a count = 0
for /f "delims=" %%a in ('dir "%~1" /a:-d /b') do (
for /F "delims=" %%b in ('find %2 ^< "%%a"') do call :next "%%b" "%~2"
)
echo found %count% occurances of "%~2"
pause
GOTO:EOF
:next
set num=0
set "line=%~1"
:nextMatch
set "line2=!line:*%~2=!"
if "!line2!" equ "!line!" goto endMatchs
set /A num+=1
set "line=!line2!"
if defined line goto nextMatch
:endMatchs
set /a count=count+num
例如:
C:> type 1.txt
An example of text file.
This example line have two "example" words.
End of example.
C:> test 1.txt "example"
found 4 occurances of "example"
这篇关于我的批处理脚本错误地计算了文件中字符串的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文