bash 比较两个文件的行,打印第一个文件独有的行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14450562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:19:31  来源:igfitidea点击:

Compare lines of two files, print lines unique to first file

bash

提问by Elliot Chance

I have two text files that contain a unique sorted list of words:

我有两个包含唯一排序单词列表的文本文件:

File 1:

文件 1:

a
b
c
d

File 2:

文件2:

b
c

I need a new file that contains only the extraneous lines in File 1, so the result will be

我需要一个仅包含文件 1 中无关行的新文件,因此结果将是

a
d

回答by kojiro

This is what commis for:

comm是为了:

comm-- select or reject lines common to two files

comm-- 选择或拒绝两个文件共有的行

You want

你要

comm -23 "File 1" "File 2"

which will suppress output of lines only in file 2and lines in both files, leaving only lines in file 1.More answers here on Greg Wooledge's wiki

这将抑制产量仅在文件2号线在这两个文件中的行,只留下行文件1.更多的答案对格雷格Wooledge的wiki在这里

回答by Rubens

You can use grep:

您可以使用grep

grep -f file1.txt -vFx file2.txt

Notice the usage of the flags F, --fixed-stringsand x, --line-regexp, to force the comparison to be performed considering the entire line.

请注意标志F, --fixed-stringsx, --line-regexp,的用法,以强制在考虑整行的情况下执行比较。

回答by Alessandro

Try this

尝试这个

$ join file1.txt file2.txt -v 1

$ join file1.txt file2.txt -v 1

$ man join

$ man join

-a FILENUM
   print unpairable lines coming from file FILENUM, where FILENUM is 1 or 2, corresponding to FILE1 or FILE2
-v FILENUM
   like -a FILENUM, but suppress joined output lines