How would you check the difference between two files with the same code? Open both files simultaneously in the editor, look at each line of code and look for differences! Maybe you can spot the differences, but it’s not super noticeable. it is complex and super-prone.
Here is a command called diff, which compares the contents of files and writes to the standard output the list of changes necessary to convert one file into the other. Diff stands for difference and is a Unix base operating system command.
To compare two files, use the following syntax:
1 |
diff [option] file1 file2 |
Now let’s take a look at 2 Python files using the cat command:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
hiwa@My-MBP Python % cat file1.py # define a function def compute_hcf(x, y): # choose the smaller number if x > y: smaller = y else: smaller = x for i in range(1, smaller+1): if((x % i == 0) and (y % i == 0)): hcf = i return hcf num1 = 54 num2 = 24 [print ("The H.C.F. is", compute_hcf (num1, num2) )% hiwa@My-MBP Python % cat file2.py # define a function def compute_hcf(x, y): # choose the smaller number if x> y: smaller = y else: smaller = x for i in range(1, smaller+1): if((x % i == 0) and (y % i == 0)): hcf = i return chf num1 = 54 num2 = 24 print("The H.C.F. is", compute_hcf (num1, num2) )% hiwa@My-MBP Python % |
Can you find the difference? Lets use diff command to find difference:
1 |
diff file1.py file2.py |
1 2 3 4 5 6 |
hiwa@My-MBP Python % diff file1.py file2.py 12c12 return hcf ーーー > return chf |
The less than and greater than symbol tells about removed and added to file.
‘c’ means changed. if you saw ‘a’ it means added and ‘d’ stands for delete.
You can use ‘-u’ flag to show the differences in unified format:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
hiwa@My-MBP Python % diff -u file1.py file2.py --- file1.py 2022-01-06 17:00:44.000000000 +0100 +++ file2.py 2022-01-06 16:53:33.000000000 +0100 @@ - 1,7 +1,7 @@ # define a function def compute_hcf(x, y) : - +# choose the smaller number if x>y: smaller = y else: @@ - 9,7 +9,8 @@ for i in range(1, smaller+1): if((x % i == 0) and (y % i == 0)): hcf = i -return hcf +return chf +#this command added for diff num1 = 54 num2 = 24 |
using the minus sign to mark lines that were removed and the plus sign to mark lines that were added.
There are many tools to compare files, diff is the most popular one. you may also use wdiff, meld KDiff3 or vimdiff.