Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare two files in UNIX

Tags:

unix

I would like to compare two files [ unsorted ] file1 and file2. I would like to do file2 - file1 [ the difference ] irrespective of the line number? diff is not working.

like image 300
Balualways Avatar asked Jan 17 '11 17:01

Balualways


People also ask

How do we compare 2 files using UNIX command?

Use the diff command to compare text files. It can compare single files or the contents of directories.

How compare multiple files in Linux?

The kdiff3 tool allows you to compare up to three files and not only see the differences highlighted, but merge the files as you see fit. This tool is often used to manage changes and updates in program code. Like vimdiff and kompare, kdiff3 runs on the desktop. You can find more information on kdiff3 at sourceforge.


2 Answers

I got the solution by using comm

comm -23 file1 file2  

will give you the desired output.

The files need to be sorted first anyway.

like image 195
Balualways Avatar answered Oct 07 '22 18:10

Balualways


Well, you can just sort the files first, and diff the sorted files.

sort file1 > file1.sorted
sort file2 > file2.sorted
diff file1.sorted file2.sorted

You can also filter the output to report lines in file2 which are absent from file1:

diff -u file1.sorted file2.sorted | grep "^+" 

As indicated in comments, you in fact do not need to sort the files. Instead, you can use a process substitution and say:

diff <(sort file1) <(sort file2)
like image 34
tonio Avatar answered Oct 07 '22 17:10

tonio