我有一系列文本文件,我想知道它们之间共有的行,而不是不同的行。命令行Unix或Windows都可以。

文件foo:

linux-vdso.so.1 =>  (0x00007fffccffe000)
libvlc.so.2 => /usr/lib/libvlc.so.2 (0x00007f0dc4b0b000)
libvlccore.so.0 => /usr/lib/libvlccore.so.0 (0x00007f0dc483f000)
libc.so.6 => /lib/libc.so.6 (0x00007f0dc44cd000)

文件栏:

libkdeui.so.5 => /usr/lib/libkdeui.so.5 (0x00007f716ae22000)
libkio.so.5 => /usr/lib/libkio.so.5 (0x00007f716a96d000)
linux-vdso.so.1 =>  (0x00007fffccffe000)

因此,对于上面的这两个文件,所需实用程序的输出类似于file1:line_number, file2:line_number ==匹配文本(只是一个建议;我真的不在乎语法是什么):

foo:1, bar:3 == linux-vdso.so.1 =>  (0x00007fffccffe000)

当前回答

以前在这里问过:Unix命令查找两个文件中的公共行

你也可以尝试用Perl:

perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/'  file1 file2

其他回答

在Windows中,你可以使用CompareObject的PowerShell脚本:

compare-object -IncludeEqual -ExcludeDifferent -PassThru (get-content A.txt) (get-content B.txt)> MATCHING.txt | Out-Null #Find Matching Lines

CompareObject:

IncludeEqual不带-ExcludeDifferent:所有 没有-IncludeEqual:什么都没有

只是为了信息,我为Windows做了一个小工具,做的事情与“grep -F -x -F file1 file2”相同(因为我在Windows上没有找到与此命令等效的任何东西)

下面就是: http://www.nerdzcore.com/?page=commonlines

Usage是“交叉引用”

源代码也是可用的(GPL)。

在*nix上,你可以使用comm,问题的答案是:

comm -1 -2 file1.sorted file2.sorted 
# where file1 and file2 are sorted and piped into *.sorted

下面是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. 

还要注意,在使用comm之前对文件进行排序是很重要的,正如手册页中提到的那样。

最简单的方法是:

awk 'NR==FNR{a[$1]++;next} a[$1] ' file1 file2

文件不需要排序。

我认为diff工具本身,使用它统一的(-U)选项,可以用来实现效果。因为diff输出的第一列标记了该行是添加还是删除,所以我们可以查找未更改的行。

diff -U1000 file_1 file_2 | grep '^ '

数字1000是任意选择的,大到比任何单个的diff输出都要大。

下面是完整的、简单的命令集:

f1="file_1"
f2="file_2"

lc1=$(wc -l "$f1" | cut -f1 -d' ')
lc2=$(wc -l "$f2" | cut -f1 -d' ')
lcmax=$(( lc1 > lc2 ? lc1 : lc2 ))

diff -U$lcmax "$f1" "$f2" | grep '^ ' | less

# Alternatively, use this grep to ignore the lines starting
# with +, -, and @ signs.
#   grep -vE '^[+@-]'

如果你想包含刚刚移动过的行,你可以在差分之前对输入进行排序,如下所示:

f1="file_1"
f2="file_2"

lc1=$(wc -l "$f1" | cut -f1 -d' ')
lc2=$(wc -l "$f2" | cut -f1 -d' ')
lcmax=$(( lc1 > lc2 ? lc1 : lc2 ))

diff -U$lcmax <(sort "$f1") <(sort "$f2") | grep '^ ' | less