比较两个文件并打印匹配项

比较两个文件并打印匹配项

有没有办法通过 Unix shell 脚本来得到这个?我有一个包含一列(1000 行)的 fileA,一个包含 26 列(13000 行)的 fileB。
我需要使用 fileB 搜索 fileA 的每个值,如果匹配则返回 FileB 中的所有 26 个值。搜索值(来自文件 A)可能出现在文件 B 的 26 个值中的任意一个中。该值在 B 文件的任何列中均不固定。

文件:

abc
def
ghi

文件B:

drm|fdm|pln|ess|abc|zeh|....|yer (26 values)
fdm|drm|def|ess|yer|zeh|....|pln

这里,abc来自 fileA 的是第 5 列。 FileB 的值 - 所以我的结果应该是 FileB 中的所有 26 个值。
同样,def文件A 中的第三列。 FileB 的值 - 所以我的结果应该是 FileB 中的所有 26 个值。

这样,需要对整个记录集进行操作。

如果不匹配,则忽略该记录。

答案1

你可以只使用grep

grep -Fwf fileA fileB

man grep

   -F, --fixed-strings
          Interpret PATTERN as a  list  of  fixed  strings,  separated  by
          newlines,  any  of  which is to be matched.  (-F is specified by
          POSIX.)
   -f FILE, --file=FILE
          Obtain  patterns  from  FILE,  one  per  line.   The  empty file
          contains zero patterns, and therefore matches nothing.   (-f  is
          specified by POSIX.)
   -w, --word-regexp
          Select  only  those  lines  containing  matches  that form whole
          words.  The test is that the matching substring must  either  be
          at  the  beginning  of  the  line,  or  preceded  by  a non-word
          constituent character.  Similarly, it must be either at the  end
          of  the  line  or  followed by a non-word constituent character.
          Word-constituent  characters  are  letters,  digits,   and   the
          underscore.

答案2

fileA 的顺序重要吗? fileB 中可以有多行具有该模式吗?例如,这将解析 fileA 并搜索 fileB 中的每个模式:

while read i; do grep "$i" fileB; done < fileA

但您需要更好地定义问题才能获得性能更高的解决方案。例如,获取整行就足够了,您不需要将其视为 26 个值。

相关内容