我的批处理脚本错误计算文件中字符串的出现次数

时间:2013-11-05 16:33:34

标签: string batch-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

我的代码是参数中指定的文本的错误计数。有什么问题?

2 个答案:

答案 0 :(得分:1)

正如Mark所说,find返回文件中匹配的的数量,而不是一行中单个字符串的数量。为此,您需要使用其他方法,例如:

@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"

答案 1 :(得分:1)

find将计算与您的字符串匹配的行数,因此搜索'xyyx'代表'x'将计为一个匹配,即使x不在一行中。如果这不是你想要的,你需要一个不同的工具。