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



我正试图编写一个批处理文件,该文件从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

生成的文件C.txt

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

我想做什么

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

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

解决方案是在fileB.txt中搜索fileA.txt中的每个单词时,将findstr结果的第一个匹配存储在fileC.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

最新更新