2

我正在尝试制作一个在文件中搜索两个不同字符串的批处理文件。然后从第一次搜索中取出第一行,从第二次搜索中取出第一行,并将它们合并为一行。

我意识到这超出了我的批量技能,因此将不胜感激。

提前致谢!


@echo off
for /f %%G in (file.txt) do (
findstr "word1" *.* > result.txt
findstr "word2" *.* >> result.txt)

例子:

文件.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

结果.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
4

1 回答 1

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
于 2013-07-10T14:56:48.627 回答