I slightly modified your program in order to convert cnt
variable into an array that have the different words as subscripts, for example cnt[Windows]=0
, cnt[Linux]=0
, etc. so :countWords
subroutine search all words in each matching line. I also eliminated the setlocal
from :countWords
subroutine in order to return the values of cnt
array in an easier way.
@echo off
setlocal EnableDelayedExpansion
set "words=Windows Linux MacOS Andriod Unix"
set file=log.txt
for %%a in (%words%) do set cnt[%%a]=0
for /f ^"eol^=^
delims^=^" %%a in ('"findstr /i "%words%" %file%"') do call :countWords "%%a"
(echo Server_Type Total_Users
for %%a in (%words%) do (
echo %%a !cnt[%%a]!
)) > result.txt
exit /b
:countWords
set wordList=%words%
:nextWord
for /F "tokens=1*" %%a in ("%wordList%") do (
set word=%%a
set wordList=%%b
)
set "ln=%~1"
:loop
if defined ln (
set "ln2=!ln:*%word%=!"
if "!ln2!" neq "!ln!" (
set "ln=!ln2!"
set /a "cnt[%word%]+=1"
goto :loop
)
)
if defined wordList goto nextWord
exit /b