需要一个批处理文件来计算文本文件中字符串的出现次数

时间:2014-03-07 16:03:04

标签: batch-file

我需要一个批处理文件来计算字符串(或多个字符串)在文本文件中退出的次数(不是行数)。可能吗?所以不是用C +,VB或任何其他语言,抱歉。

Ex:file test.txt:

today i was shopping for the 10th consecutive day,
even I was not feeling well and the day was a Sunday

字符串是“我”和“日”这应该给我结果:

i - 5 times, day - 4 times

1 个答案:

答案 0 :(得分:0)

对要查找的每个字符串运行此命令。

@echo off
setlocal enabledelayedexpansion
:: Base code by Tom Lavedas ::
set recurse=
if "%~1%~2"=="%~1" goto :EOF
if "%~3"=="" (set count=0 & %0 %1 %2 %2)
    for /f "delims=" %%f in ('findstr /m "%~2" "%1"') do (
        set count=0
        for /f %%a in ('type "%%f" ^| findstr "%~2"') do (
          set search=%~2
          set file=%%f  
          set /a count +=1
          set /a tcount +=1
        )
    echo !search! found !count! times in !file!
    set recurse=%0 %1 "%~2.*%~3" "%~3"
    )
%recurse%
Echo(Total count: !tcount!
exit /b