两个文件之间的交叉点

时间:2016-04-13 09:23:23

标签: linux

我是编程的第一时间,我试图找到两个文本文件的交集。

file1.txt
a a
a b
a a
a c

file2.txt
a a

我想在file1 file2中的file1中的行

中得到以下结果
a a
a a

我尝试在Linux中使用grep命令,但我不知道该怎么做。

2 个答案:

答案 0 :(得分:3)

我在这里看到类似的东西https://stackoverflow.com/a/36591385/4053813

< file1 xargs -I % grep -xF '%' file2

编辑:正如@Julien Lopez所指出的,我为grep命令添加了-xF选项。

答案 1 :(得分:2)

使用grep

grep -xFf file2.txt file1.txt

-F, --fixed-strings
          Interpret  PATTERN  as  a  list  of  fixed  strings (rather than
          regular expressions), separated by newlines, any of which is  to
          be matched.
-f FILE, --file=FILE
          Obtain patterns  from  FILE,  one  per  line.   The  empty  file
          contains zero patterns, and therefore matches nothing.
-x, --line-regexp
          Select only those matches that exactly  match  the  whole  line.
          This option has the same effect as anchoring the expression with
          ^ and $.