例如我有内容
的文本文件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,但我想只打印每个第一次出现,换句话说,它将跳过第一个搜索字符串并继续搜索下一个字符串。所以结果将是这样的:
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
答案 0 :(得分:0)
@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
。
答案 1 :(得分:0)
@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