我正在尝试创建一个批处理文件,用于在文件中搜索两个不同的字符串。然后从第一次搜索中获取第一行,从第二次搜索中获取第一行,并将它们分成一行。
我意识到这是我的批量技能,所以会有一点帮助。
提前致谢!
@echo off
for /f %%G in (file.txt) do (
findstr "word1" *.* > result.txt
findstr "word2" *.* >> result.txt)
示例:
file.txt的:
hello i'm a line with word1
hello i'm a line with word2
hello i'm another line with word1
hello i'm another line with word2
hello i'm yet another line with word1
hello i'm yet another line with word2
的Result.txt:
hello i'm a line with word1hello i'm a line with word2
hello i'm another line with word1hello i'm another line with word2
hello i'm yet another line with word1hello i'm yet another line with word2
答案 0 :(得分:3)
设置要在变量PairsToShow
中显示的线对数:
@ECHO OFF &SETLOCAL
SET "FileName=file.txt"
SET "Word1=word1"
SET "Word2=word2"
SET /a PairsToShow=3
SET /a Lines1=0, Lines2=0
FOR /f "delims=" %%a IN ('findstr "%Word1%" "%FileName%"') DO (
SET "str=%%a"
SET /a Lines1+=1
SETLOCAL enabledelayedexpansion
SET "$1!Lines1!=!str!"
FOR /f "tokens=1*delims==" %%b IN ('set "$1"') DO (IF "!"=="" endlocal)&SET "%%b=%%c"
)
FOR /f "delims=" %%a IN ('findstr "%Word2%" "%FileName%"') DO (
SET "str=%%a"
SET /a Lines2+=1
SETLOCAL enabledelayedexpansion
SET "$2!Lines2!=!str!"
FOR /f "tokens=1*delims==" %%b IN ('set "$2"') DO (IF "!"=="" endlocal)&SET "%%b=%%c"
)
SET /a Lines=Lines1+Lines2
ECHO(%Lines% lines read from %FileName%.
IF %Lines1% leq %Lines2% (SET /a MaxPairs=Lines1) ELSE SET /a MaxPairs=Lines2
IF %PairsToShow% gtr %MaxPairs% (
ECHO only text for %MaxPairs% pairs NOT %PairsToShow% :/
GOTO :END
)
(FOR /l %%a IN (1,1,%PairsToShow%) DO (
SETLOCAL ENABLEDELAYEDEXPANSION
CALL SET "Line1=%%$1%%a%%"
CALL SET "Line2=%%$2%%a%%"
<NUL SET /p "=!Line1!"
ECHO !Line2!
ENDLOCAL
))> result.txt
ENDLOCAL
TYPE result.txt
:END
PAUSE