我确信我曾经发现过一个shell命令,它可以从两个或多个文件中打印公共行。它叫什么名字?

它比diff简单多了。


当前回答

要轻松地将comm命令应用到未排序的文件,请使用Bash的进程替换:

$ bash --version
GNU bash, version 3.2.51(1)-release
Copyright (C) 2007 Free Software Foundation, Inc.
$ cat > abc
123
567
132
$ cat > def
132
777
321

因此,文件abc和def有一行相同的行,即带有“132”的行。 对未排序的文件使用comm:

$ comm abc def
123
    132
567
132
    777
    321
$ comm -12 abc def # No output! The common line is not found
$

最后一行没有输出,公共行没有被发现。

现在使用comm对已排序的文件进行排序,使用进程替换对文件进行排序:

$ comm <( sort abc ) <( sort def )
123
            132
    321
567
    777
$ comm -12 <( sort abc ) <( sort def )
132

现在我们到了132线!

其他回答

rm file3.txt

cat file1.out | while read line1
do
        cat file2.out | while read line2
        do
                if [[ $line1 == $line2 ]]; then
                        echo $line1 >>file3.out
                fi
        done
done

这个应该可以了。

为了补充Perl的一行代码,下面是它在awk中的等价代码:

awk 'NR==FNR{arr[$0];next} $0 in arr' file1 file2

这将把file1中的所有行读入数组arr[],然后检查file2中的每一行是否已经存在于数组中(即file1)。找到的行将按照它们在file2中出现的顺序打印出来。 请注意,arr中的比较使用从file2开始的整行作为数组的索引,因此它只报告整行上的精确匹配。

这不是你想问的,但我认为这对于描述一个稍微不同的场景还是有用的

如果你只是想快速确定一堆文件之间是否有重复的行,你可以使用这个快速解决方案:

cat a_bunch_of_files* | sort | uniq | wc

如果你得到的行数比你得到的少

cat a_bunch_of_files* | wc

然后是一些重复的线条。

awk 'NR==FNR{a[$1]++;next} a[$1] ' file1 file2
perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/'  file1 file2