比较linux中的两个未排序列表,列出第二个文件中唯一的

问题描述 投票:0回答:5

我有 2 个包含号码列表(电话号码)的文件。

我正在寻找一种方法来列出第二个文件中第一个文件中不存在的数字。

我尝试了各种方法:

comm (getting some weird sorting errors)
fgrep -v -x -f second-file.txt first-file.txt (unsure of the result, there should be more)
linux bash shell comparison grep
5个回答
88
投票
grep -Fxv -f first-file.txt second-file.txt

基本上查找

second-file.txt
中与
first-file.txt
中任何行不匹配的所有行。如果文件很大,可能会很慢。

此外,一旦对文件进行排序(如果它们是数字,则使用

sort -n
),那么
comm
也应该起作用。它给出了什么错误?试试这个:

comm -23 second-file-sorted.txt first-file-sorted.txt

31
投票

您需要使用

comm

comm -13 first.txt second.txt

会完成这项工作。

ps。命令行中第一个和第二个文件的顺序很重要。

您可能还需要先对文件进行排序:

comm -13 <(sort first.txt) <(sort second.txt)

如果文件是数字,请将

-n
选项添加到
sort


14
投票

这应该有效

comm -13 <(sort file1) <(sort file2)

似乎 sort -n (数字)无法与 comm 一起使用,comm 在内部使用 sort (字母数字)

f1.txt

1
2
21
50

f2.txt

1
3
21
50

21 应出现在第三列

#WRONG
$ comm <(sort -n f1.txt) <(sort -n f2.txt)   
                1
2
21
        3
        21
                50

#OK
$ comm <(sort f1.txt) <(sort f2.txt)
                1
2
                21
        3
                50

1
投票
cat f1.txt f2.txt | sort |uniq > file3

0
投票

如果您有两个已排序的文件,

diff
就是为此而设计的:

diff -y --suppress-common-lines --color=always sorted_list1.txt sorted_list2.txt | less
© www.soinside.com 2019 - 2024. All rights reserved.