dragon_sa
dragon_sa

Reputation: 49

Batch file to print first match of findstr results only to text file

Im trying to write a batch file that reads a list from fileA.txt then checks fileC.txt if match exists, if match not exist write first matching line only from fileB.txt to fileC.txt

fileA.txt example

aaa1
aaaa
aaaa4
bbb
ccc12

fileB.txt example

aaa1 some text
aaa1 blah bla
aaa1 .r
aaaa some info
aaaa blah bla
aaaa4 some name
bbb some name to
bbb more blah blah
ccc12 another name
ccc12 blah bla

resulting fileC.txt

aaa1 some text
aaaa some info
aaaa4 some name
bbb some name to
ccc12 another name

What Im trying to do

for /F %%i in (C:\filecopy\fileA.txt) do (
If exist (findstr /B /C:%%i fileC.txt) (
echo %%i exists ) else (
findstr /B /C:%%i fileB.txt >> fileC.txt )
)

But that code isnt correct and im not sure how best to handle it

Upvotes: 2

Views: 7004

Answers (1)

Aacini
Aacini

Reputation: 67206

The solution is to store in fileC.txt just the first match of findstr result when each word in fileA.txt is searched in fileB.txt (precisely as you indicated in the question title):

@echo off
setlocal

(for /F %%i in (fileA.txt) do (
   set "firstMatch=true"
   for /F "delims=" %%j in ('findstr /B /C:%%i fileB.txt') do (
      if defined firstMatch (
         echo %%j
         set "firstMatch="
      )
   )
)) > fileC.txt

Upvotes: 1

Related Questions