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

时间:2016-04-29 06:08:37

标签: batch-file if-statement cmd 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

生成的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 )
)

但是那段代码是不正确的,我不知道如何最好地处理它

1 个答案:

答案 0 :(得分:1)

解决方法是在fileB.txt中搜索fileA.txt中的每个单词(正如您在问题标题中所指示的那样),将文件存储在fileC.txt中 findtr结果的第一个匹配

@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