使用findstr进行多字符串AND搜索

时间:2013-12-13 19:42:37

标签: regex batch-file findstr

使用下面我能够计算单个单词的出现次数并获得结果如下所示。

@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

现在我想添加6个新单词,如Linux,MacOS,Andriod,Unix ....等,在同一个日志文件中搜索并获得相同格式的结果。

但没有得到如何使用FINDSTR实现这一点,并且鉴于Findstr的RegExp功能有限,这可能吗?有什么建议吗?

3 个答案:

答案 0 :(得分:1)

我还没试过这个,但概念如下:

@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>
...
)

答案 1 :(得分:1)

我稍微修改了您的程序,以便将cnt变量转换为具有不同单词作为下标的array,例如cnt[Windows]=0cnt[Linux]=0等。 :countWords子例程搜索每个匹配行中的所有单词。我还从setlocal子例程中删除了:countWords,以便更容易地返回cnt数组的值。

@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

答案 2 :(得分:0)

获取计数的一种更简单的方法:您只需在搜索字符串的名称前加上一个#,并使用Set /a #%%a+=1增加此新变量的值(如果字符串真的相同),然后使用set #你得到了所有的指控。非常简单高效。 (对不起我可怕的英语)

@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
相关问题