第2个回答 2021-06-25
不清楚你的实际文件/情况,仅以问题中的样例/说明为据;以下代码复制粘贴到记事本,另存为xx.bat,编码选ANSI,跟要处理的文件放一起双击运行
<# :
cls&echo off
rem 统计一个指定字符串在一个txt文本文件里出现的次数
set #=Any question&set @=WX&set $=Q&set/az=0x53b7e0b4
title %#% +%$%%$%/%@% %z%
cd /d "%~dp0"
powershell -NoProfile -ExecutionPolicy bypass "Invoke-Command -ScriptBlock ([ScriptBlock]::Create([IO.File]::ReadAllText('%~f0',[Text.Encoding]::GetEncoding('GB2312'))))"
echo;%#% +%$%%$%/%@% %z%
pause
exit
#>
$txtfile="xxx.txt";
$findword="指定字符串";
if(-not (test-path -liter $txtfile)){write-host ('"'+$txtfile+'" 未找到');exit;};
$text=[IO.File]::ReadAllText($txtfile, [Text.Encoding]::GetEncoding('GB2312'));
$index=0;
$count=0;
while(($index=$text.IndexOf($findword, $index)) -ne -1){
$count++;
$index=$index+$findword.Length;
}
write-host $count;