Search code examples
batch-filecmdfindstr

findstr multiple search string and print each occurrence only the first line


for example i have text file with content

superman
batman
hello world
sport cars
hello world2
jackie chan
flower
supermom
hello world3
clock
fried chicken
microsoft
flower boy
flash dance
flower girl
flowerwoman
sun flower
what the hello

i want to create a batch file using findstr with multiple search string, for example: hello and flower, but i want to print only the first occurence each, in other words, it will skip the first search string and move on to search the next string. so the result will be like this:

hello world
flower
hello world3
flower boy
what the hello

is this possible? i can print all the occurence found in multiple files to output.txt with this code

@echo off
>"output.txt" (
  for %%F in (*.txt) do (
    findstr /c:"hello" /c:"flower" "%%F"
    (echo()
  )
)
findstr . "output.txt" >"output.txt.new"
move /y "output.txt.new" "output.txt" >nul
type output.txt

Solution

  • @echo off
    setlocal EnableDelayedExpansion
    
    set "word[0]=hello"
    set "word[1]=flower"
    set "lastFind="
    
    >"output.tmp" (
       for %%F in (*.txt) do (
          for /F "delims=" %%a in ('findstr /c:"%word[0]%" /c:"%word[1]%" "%%F"') do (
             set "line=%%a"
             if not defined lastFind (
                if "!line:%word[0]%=!" equ "!line!" (set lastFind=0) else set lastFind=1
             )
             for %%b in (!lastFind!) do for /F %%c in ("!word[%%b]!") do if "!line:%%c=!" equ "!line!" (
                echo !line!
                set /A "lastFind=(lastFind+1)%%2"
             )
          )
          rem Activate next line to restart the seek in each file
          REM set "lastFind="
       )
    )
    ren output.tmp output.txt
    type output.txt