:: 统计重复次数 setlocal enabledelayedexpansion for /f %%i in (tmp1.txt) do ( set /a num+=1 set second=!first! set first=%%i if not "!second!"=="" if !second! neq !first! (>>tmp2.txt echo !second! !num!&set num=0) ) >>tmp2.txt echo %first% %num%
:: 对重复次数排序 md tmp && pushd tmp for /f "tokens=2" %%i in (../tmp2.txt) do ( cd.>%%i for /l %%j in (1,1,%%i) do echo.>>%%i ) >../tmp3.txt dir /o-s /b
:: 按重复次数提取记录 for /f %%i in (../tmp3.txt) do ( >>../result.txt findstr " %%i$" ../tmp2.txt ) popd && rd /q /s tmp del tmp1.txt tmp2.txt tmp3.txt start result.txt goto :eof
关于统计字符出现个数的其他方案(都不生成临时文件)
@echo off :: 统计每个字符出现的次数,并求出出现次数最多的字符 :: 思路: :: 通过提取每个位上的字符,赋予统一以 字符: 开头的某些动态变量, :: 如果变量名相同,则自加一次,然后,通过 set 字符:命令一次性提取 :: 所有以 字符: 开头的动态变量,交给 for 语句来处理。set 用得很巧妙 :: 无须生成临时文件,并按照字母升序排列 :: :: ::
setlocal ENABLEDELAYEDEXPANSION set str=adadfdfseffserfefsefseetsdmg set /a m=0,n=0,l=0
call :loop
:: 以下是求出现次数最多的字符 for /f "tokens=1,2 delims==" %%i in ('set 字符:') do ( echo %%i=%%j if %%j GTR !l! set l=%%j& set m=%%i )
echo.出现次数最多的%m%=%l% pause goto :EOF
:loop call set m=%%str:~%n%,1%% if not defined m goto :EOF set /a "字符:%m%+=1" set /a n+=1 goto loop