Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output difference between two text files? [closed]

I'm wondering how I can compare two text files, highlighting the difference between each of them? For example:

File1.txt

AAAAA
BBBBB
CCCCC

File2.txt

AAAAA
BBBBB

I'd like to have the following output after comparison of those two files:

CCCCC

I'm using Python, and tried sed and grep with no luck (I'm interested in linux shell ways of doing this too).

like image 696
roger herbert Avatar asked Sep 21 '25 02:09

roger herbert


2 Answers

Python has a library specifically for doing exactly this: difflib. You can feed it the contents of two text files and it will return back differences between the two.

For an example, see http://pymotw.com/2/difflib/

like image 155
Bryan Oakley Avatar answered Sep 22 '25 15:09

Bryan Oakley


I used this in python, is simple, but it works

>>> File1 = open("file1","r")
>>> File2 = open("file2","r")
>>> Dict1 = File1.readlines()
>>> Dict2 = File2.readlines()
>>> print Dict1
['AAAAA\n', 'BBBBB\n', 'CCCCC\n']
>>> print Dict2
['AAAAA\n', 'BBBBB\n']
>>> DF = [ x for x in Dict1 if x not in Dict2 ]
>>> print DF
['CCCCC\n']
>>> print DF[0]
CCCCC

>>> print DF[0].rstrip()
CCCCC
like image 20
c4f4t0r Avatar answered Sep 22 '25 15:09

c4f4t0r