批处理文件仅将 findstr 结果的第一个匹配项打印到文本文件

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

我正在尝试编写一个批处理文件,该文件从 fileA.txt 读取列表,然后检查 fileC.txt 是否存在匹配项,如果不存在匹配项,则只写入从 fileB.txt 到 fileC.txt

fileA.txt 例子

aaa1
aaaa
aaaa4
bbb
ccc12

fileB.txt 例子

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

结果 fileC.txt

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

我想做什么

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 )
)

但该代码不正确,我不确定如何最好地处理它

解决方案是在fileC.txt中只存储findstr结果的第一个匹配项,当fileA.txt中的每个词在fileB.txt中被搜索时(正如您在问题标题中指出的那样):

@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