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

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

4

2 回答 2

1

正如马克所说,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"
于 2013-11-05T18:26:39.873 回答
1

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

于 2013-11-05T18:31:23.503 回答