Why do we use sort before compare ?

Dear All.

Im trying to know how exactly the command "compare" works, does it compare line by line or field by field, and the most important thing is that why the files have to be sorted before we compare them?

Thanks in advance

What "compare" command are you referring to? Diff? comm? cmp?

As to why sort before compare, imagine you have two phone books: one from last year and one from this year. Could you simply compare the two books, line by line? Yes. Now imagine someone had taken one of the phonebooks, torn out each page and thrown all the pages around the house. Now how will you compare the two? First you would reorganize it so the torn-up phonebook was in its original order. Then you could compare line by line.

Does that help?

Yes you are right, but what if I rearrange the pages of my phone book in different order, I can still compare both of my phone books. Am I right ?

I will match my first line of my first book with all the pages of the second phone book even if they are not sorted.

ofcourse this doesn't work with diff or comm commands?

I hope that I made my point clearer...

Sound more like a grep command then.

egrep -f "myfile" "mykeyword"
(or something like that)

Where you are checking to see if someone from the first book exists on any page from the second book.

If you use the same ordering for both phone books. You could, for instance, sort with reverse (sort -r). Or you could sort by the second character and then the rest of the string (sort -k 1.2,1.3 -k 1,0)

Not really.

Please understand ..... Im just wondering about "why we have to sort before we compare 2 files " .... Im not asking how to sort....

Your example about phone book is not good enough to show the reason behind " sorting before comparing 2 files "

Did you understand now...

also please Mr. joeyg .... read the thread then answer....

The short answer is: it's the only way to find a reasonably small change-set between two files. For the long answer, perhaps you should look up research papers on sorting and searching. Or, take some phone books and try it yourself.

what a funny guy........:eek: