比较两个文本文件

我有两个大的csv文件,file1.csv看起来像这样

1,2,3,4 1,4,5,6 1,7,8,9 1,11,13,17 

file2.csv看起来像这样

 1,2,3,4 1,7,8,9 2,4,9,10 13,14,17,18 

这些只是我编写的随机数,基本上是两个相同的数字,并进行了排序。 我想比较file1.csv和file2.csv,然后将file1.csv中但不存在于file2.csv中的行复制到file3.csv。 分隔符显然是逗号

我试过了

 comm -2 -3 file.csv file2.csv > file3.csv 

我试过

 diff -u file.csv file2.csv >> file3.csv 

两者都不起作用,因为file3比file1和file2大。 我尝试了不同的diffcomm命令,有时它比file2大,与文件file1的大小差不多,我知道file3的大小必须远小于file1和file2。 当然,我查看了file3,而不是我想要的结果

此时,我知道可以使用diffcomm完成,但我不知道要使用的命令。

试试这个命令:

  grep -v -f file2.csv file1.csv > file3.csv 

根据grep手册 :

  -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.) -v, --invert-match Invert the sense of matching, to select non-matching lines. (-v is specified by POSIX.) 

正如Steeldriver在他的评论中所说的那样,最好还添加-x-F

  -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.) -x, --line-regexp Select only those matches that exactly match the whole line. (-x is specified by POSIX.) 

所以,更好的命令是:

  grep -xvFf file2.csv file1.csv > file3.csv 

此命令使用file2.csv行作为模式和不匹配的file1.csv打印行( -v )。

为了能够使用comm ,您必须先对行进行排序。

 comm -23 <(sort file1.csv) <(sort file2.csv) > file3.csv 

一个python选项:

 #!/usr/bin/env python3 import sys def readfile(file): with open(file) as src: return [line.strip() for line in src.readlines()] lines_1 = readfile(sys.argv[1]); lines_2 = readfile(sys.argv[2]) for line in lines_1: if not line in lines_2: print(line) 

输出:

 1,4,5,6 1,11,13,17 

将脚本粘贴到一个空文件中作为extract.py ,使其可执行并通过以下命令运行它:

  

或者,将其直接写入file_3:

  

使用diff命令执行grep并且不需要存储。

如果行存在于file1但不存在于file2中,则输出:

 $ diff file{1,2}.csv | grep -Po "^< \K.*" 1,4,5,6 1,11,13,17 

如果行存在于file2但不存在于file1中,只输出左角( < )到直角( > ),则输出:

 $ diff file{1,2}.csv | grep -Po "^> \K.*" 2,4,9,10 13,14,17,18