:: 統計重復次數 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