34

I have two files which the order of lines is irrelevant, and I want to compare its content.

I looked into diff documentation but could not find anything like --ignore-order.

Any tips?

1

3 Answers 3

71

Sort the files first:

$ sort file1 > file1.sorted
$ sort file2 | diff - file1.sorted

Also, although I personally discourage this sort of thing, if you are using bash and this feature is enabled on your system you can avoid the temporary file by using a process substitution:

$ diff <(sort file1) <(sort file2)
0
2

Not bash, but still fast way using python:

def check_diff(file1,file2):
    check = {}
    for file in [file1,file2]:
        with open(file,'r') as f:
            check[file] = []
            for line in f:
                check[file].append(line)
    diff = set(check[file1]) - set(check[file2])
    for line in diff:
        print(line.rstrip())
1

Maybe you're looking at the problem from the wrong side. Perhaps you would like to sort both files and then compare them?

Otherwise,

diff file1 file2 

would do exactly what you are asking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.