0

Need exact output of difference between two files. Data was in rows separated by comma and there was number of rows, for example I have shown you only one row. Each string should look for every string in other file.

example:

file1.txt

abc,def,ghi,klm,nop
one,two,three,four,five,six

file2.txt

abc,def,ghi,klm,nop
one,two,three,test,four,five,six

expected output:

test
  • 1
    a quick one grep -ho '[^,]*' file1.txt file2.txt | sort | uniq -u but I am not sure if it would work for OP's real input – Sundeep May 5 '17 at 3:41
  • What should be the output if the second file contains not test but te,st? – Kusalananda May 5 '17 at 9:54
  • ... and what about "te,st"? I'm fishing for whether it's needed to do proper CSV file parsing or not. – Kusalananda May 5 '17 at 10:17
2

Python approach with difflib (Helpers for computing deltas) and sys modules:

differ.py:

import difflib, sys

with open(sys.argv[1], 'r') as f1, open(sys.argv[2], 'r') as f2:
    differ = difflib.Differ()
    for l in differ.compare(f1.read().split(','), f2.read().split(',')):
        if (l.startswith('+ ') or l.startswith('- ')):
            sys.stdout.write(l[2:] + '\n')

Usage:

python differ.py file1.txt file2.txt

The output:

test

difflib.Differ - a class for comparing sequences of lines of text, and producing human-readable differences or deltas

0

The all time classic gnu awk approach:

awk -v RS=",|\n" 'NR==FNR{seen[$0]++;next}!seen[$0]' file1 file2 
test

This works because we are using also comma as awk line/record separator (RS), and thus we get an output like this for each file:

awk -v RS=",|\n" '{print $0}' file1
abc
def
ghi
klm
nop
one
two
three
four
five
six
  • @Sundeep I lost your point... this awk will work even if last two entries are swapped. What is the bug you found...? – George Vasiliou May 5 '17 at 14:15
  • 1
    @Sundeep You were right. Answer updated. Now seems to work ok. – George Vasiliou May 5 '17 at 20:49
  • @sam answer updated – George Vasiliou May 5 '17 at 20:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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