如何从Linux中的两个文件中删除相同的行

时间:2020-03-05 15:27:17  来源:igfitidea点击:

如何从Linux中的两个文件中删除包含匹配文本的行?
让我们讨论如何使用Linux Comm和Sout命令执行此任务。

假设,我们有两个文件,例如file1和file2,具有以下内容:

$cat file1
[email protected]
[email protected]
[email protected]
[email protected]
$cat file2
[email protected]
[email protected]

目的是获取包含文件1唯一的内容的文件(从File1中删除File2的匹配行)。

因此,生成的文件应如下。

$cat file3
[email protected]
[email protected]

这可以通过Linux命令"Comm"来完成。
此命令的基本语法如下:

comm [-1] [-2] [-3 ] file1 file2
-1 Suppress the output column of lines unique to file1.
-2 Suppress the output column of lines unique to file2.
-3 Suppress the output column of lines duplicated in file1 and file2.
file1 Name of the first file to compare.
file2 Name of the second file to compare.

在应用"Comm"之前,我们需要对输入文件进行排序。
因此,为了让File1唯一的行,我们可以使用"Comm"和"Sort"命令的组合如下。

$comm -23 <(sort file1) <(sort file2) > file3

上面的命令将使用file1和file2的唯一内容创建File3文件。