2013-07-10 77 views
2

我正在嘗試製作一個批處理文件,用於在文件中搜索兩個不同的字符串。然後從第一個搜索中取第一行,從第二個搜索中取第一行,並將它們組合成一行。搜索兩個字符串,然後將結果加在一起

我意識到這是對我的技能批量的方式,所以一點幫助,將不勝感激。

在此先感謝!


@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

向我們展示您到目前爲止的內容。 SO不是「爲我免費編寫代碼」類型的網站。 –

+0

如此編輯我目前的工作 – user2553264

+0

這兩個單詞是固定的,還是來自'file.txt'? –

回答

3

集合L的數量ine對顯示在變量中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 
+0

我得到所有與「word1」和「word2」的行,但我需要word1搜索的第一行和從word2搜索的第一行是一行 例如:file.txt:你好我是一個線word1 你好我是line2 result.txt:你好我是word1hello的一條線我是word2的一條線 – user2553264

+0

@ user2553264你可以試試我的編輯:) – Endoro

+0

謝謝你的回答!但我只得到這個: file.txt:你好,我是一個字word1 file.txt:你好我是一個字word2 在result.txt 它是否適合你? – user2553264

相關問題