![如何使用批处理文件计算文件中特定字符串的所有出现次数?](https://linux22.com/image/1457219/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%E6%89%B9%E5%A4%84%E7%90%86%E6%96%87%E4%BB%B6%E8%AE%A1%E7%AE%97%E6%96%87%E4%BB%B6%E4%B8%AD%E7%89%B9%E5%AE%9A%E5%AD%97%E7%AC%A6%E4%B8%B2%E7%9A%84%E6%89%80%E6%9C%89%E5%87%BA%E7%8E%B0%E6%AC%A1%E6%95%B0%EF%BC%9F.png)
setlocal EnableDelayedExpansion
for /f %%C in ('Find /C "pdf" ^< %CD%\sample.txt') do set Count=%%C
echo Found = !Count! time/s >> xerox.log
echo Found = %%C time/s
pause
这是我的批处理文件。它在整个文件中查找并计算单词“pdf”,但按行进行计算。它不计算所有出现的次数。我如何计算所有出现的次数?
答案1
如何在文件中找到所有出现“pdf”一词的地方?
使用以下批处理文件。
测试命令
@echo off
setlocal
setlocal EnableDelayedExpansion
set _count=0
set _match=pdf
set _file=abc.txt
for /f "tokens=*" %%i in (%_file%) do (
set _line=%%i
call :match
)
goto :done
:match
for /f "tokens=1,*" %%a in ("%_line%") do (
set _word=%%a
set _line=%%b
)
if /i "%_word%"=="%_match%" set /a _count=!_count!+1
if "%_line%"=="" goto :eof
goto :match
:done
echo."pdf" was found !_count! times.
endlocal
- 替换
abc.txt
为包含您的 txt 的文件名。 - 根据需要
echo."pdf" was found !_count! times.
用您自己的命令替换。echo
ABC文件
abc pdf def pdf
pdf
pdf pdf pdf
abc def ghi
示例用法
F:\test>test
"pdf" was found 6 times.
F:\test>
如果 txt 文件是这样的,abc.pdf def.pdf pdf pdf pdf pdf abc def ghi
它只计算 4
在这种情况下,第二个for /f
命令需要更改为使用.
和(默认值)作为匹配的分隔符。
替换后的行如下:
for /f "tokens=1,* delims=. " %%a in ("%_line%") do (
delims=.
已添加。
进一步阅读
- 为了- 有条件地多次执行命令
- Windows CMD 命令行的 AZ 索引- 与 Windows cmd 行相关的所有事物的绝佳参考。