findstr 多次搜索字符串并仅打印第一行

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

例如我有内容为

的文本文件
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

我想使用带有多个搜索字符串的 findstr 创建一个批处理文件,例如:hello 和 flower,但我只想打印每个第一次出现的地方,换句话说,它将跳过第一个搜索字符串并移动on 搜索下一个字符串。所以结果会是这样的:

hello world
flower
hello world3
flower boy
what the hello

这可能吗?我可以使用此代码

将在多个文件中找到的所有事件打印到 output.txt
@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
@echo off
setlocal enableDelayedExpansion

set "MATCH1=hello"
set "MATCH2=flower"

>"output.txt" (
  for %%F in (*.txt) do if not %%~nxF==output.txt (
    set matchIndex=0
    set expectedMatch=%MATCH1%
    for /f "delims=" %%a in ('findstr /c:"%MATCH1%" /c:"%MATCH2%" "%%F"') do (
        echo %%a | find "!expectedMatch!" >nul
        if !matchIndex!==0 (
            set matchIndex=1
            if errorlevel 1 set matchIndex=2 & ver>nul
        )
        if not errorlevel 1 (
            echo %%a
            set /a matchIndex=!matchIndex! %% 2 + 1
            call set "expectedMatch=%%MATCH!matchIndex!%%"
        )
    )
  )
)
type output.txt
pause

目前预期的匹配索引被重置为每个新 *.txt 文件的第一个搜索字符串,因此如果您想要在文件之间连续更改字符串,只需在第一个循环之前移动 set matchIndex=1

@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