Question

Using below I was able to count total number of occurrences of a single word and getting result as given below.

@echo off
set "word=Windows"
set file=log.txt
set cnt=0
for /f ^"eol^=^

delims^=^" %%a in ('"findstr /i "/c:%word%" %file%"') do set "ln=%%a"&call :countWord

echo Server_Type   Total_Users    >result.txt
echo %word%           %cnt%       >>result.txt
exit /b

:countWord
setlocal enableDelayedExpansion
:loop
if defined ln (
set "ln2=!ln:*%word%=!"
if "!ln2!" neq "!ln!" (
  set "ln=!ln2!"
  set /a "cnt+=1"
  goto :loop
)
  )
endlocal & set cnt=%cnt%
exit /b

result.txt

Server_Type  Total_Users
Windows          24

now i want to add 6 new words like Linux, MacOS, Andriod, Unix....etc to search for in the same log file and get result in same format.

but not getting how to achieve that using FINDSTR and Is that possible given the limited RegExp capability of Findstr ? any suggestion please ?

Was it helpful?

Solution

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

OTHER TIPS

I've haven't tried this, but the concept would be such as:

@echo off
set "word=Windows Linux MacOS ..."
set file=log.txt
set cnt=0
for %%i in (%word%) do (
for /f ^"eol^=^
...
<the rest of your code>
...
)

An easier way to get the counts : you just put a # before the name of the searching string and increase the value of this new Variable (if the string is really the same) with Set /a #%%a+=1 and then with a set # you get all your counts. Very simple and efficient. (sorry for my terrible english)

@ECHO OFF

set "$file=log.txt"
set "$Lsearch=windows unix linux macOs Android"


for %%a in (%$LSearch%) do (set #%%a=0
                  for /f "delims=" %%* in ('type %$file% ^| findstr /i "%%a"') do if /i "%%*"=="%%a" set /a #%%a+=1)

for /f "tokens=1,2 delims==" %%a in ('set #') do echo Server : %%a Total User : %%b
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top