比较两个文件的相同行,其中顺序无关紧要

时间:2010-11-12 13:47:48

标签: file comparison

我有两个文件(可能长达150,000行;每行是160个字节),我想查看每个文件中的行是否相同。 diff对我(直接)不起作用,因为一小部分行在两个文件中以不同的顺序出现。通常,一对线将被转置 查看两个文件中是否出现相同行的最佳方法是什么,但顺序无关紧要? 谢谢, 克里斯

3 个答案:

答案 0 :(得分:4)

虽然这是一种稍微昂贵的方式(对于任何更大的我都会重新考虑这个),我会启动python并执行以下操作:

filename1 = "WHATEBVER YOUR FILENAME IS"
filename2 = "WHATEVER THE OTHER ONE IS"
file1contents = set(open(filename1).readlines())
file2contents = set(open(filename2).readlines())
if file1contents == file2contents:
    print "Yup they're the same!"
else:
    print "Nope, they differ.  In file2, not file1:\n\n"
    for diffLine in file2contents - file1contents:
        print "\t", diffLine
    print "\n\nIn file1, not file2:\n\n"
    for diffLine in file1contents - file2contents:
        print "\t", diffLine

如果它们不同,那将打印不同的行。

答案 1 :(得分:1)

对于仅150k行,只需散列每行并将它们存储在查找表中。然后,对于文件2中的每一行,只需执行查找。

答案 2 :(得分:0)

另一个执行此操作的python脚本:

#!/usr/bin/env python
import sys

file1 = sys.argv[1]
file2 = sys.argv[2]

lines1 = open(file1,'r').readlines()
lines2 = open(file2,'r').readlines()
lines1.sort()
lines2.sort()

s = ''
for i,line in enumerate(lines1):
    if lines2[i] != line:
        print '> %s' % line
        print '< %s' % lines2[i]
        s = 'not'

print 'file %s is %s like file %s' % (file1, s, file2)
相关问题