Monday, August 8, 2016

How to compare two files in Linux

There are various tools provided in various linux flavors to compare two text files, but there are few common ways of doing this i as below.

1. Using "diff" command.
    It compare two files line by line and list out the differences.

    Syntax: diff [options] file1 file 2
 
     Options: options can be used to change behavior of command scope
                    -b Instruct the system to ignore extra spaces and tabs.
                    -w Ignore all white spaces
                    -i Ignore any case differences
                    -E Ignore changes due to tab expansion.
                    -c useful in comparing tow code files and points ! to indicate difference,- for less and +                             for  more
                    <for more options refer manual>
 
     Example:
   
                 file1:
                         1
                         2
                         3
                         4
                         5
                         6
                         7
                         8
                         9

                 file2:
                        1
                        2
                        3
                        7
                        8
                        9
                       10
                       11
                       16
     
            $ diff file1 file2


                4,6d3
                < 4
                < 5
                < 6
               9a7,9
                > 10
                > 11
                > 16

The output is produced in ED line editor format, which suggest what changes to file will make it same as other file being compared. in above example 4,6d3 means delete 3 lines from 4-6 in first file and 9a7,9 means append at 9th position line 7-9 from second file.

Note: diff can be used to compare files in two different directory.

2. Using "vimdiff" or "vim -d" text editor functionality
    this tool will display the difference in file in vertical column and highlighting the difference.

    Syntax: vimdiff file1 file2

    Example: vimdiff 1 2 or vim -d 1 2


   
3. Using "comm" command
     This command will compare the files and will display the difference in  3 column.

    Syntax: comm [-123i] file1 file2
                  -1 to display difference in 1st file compared to 2nd file
                  -2 to display difference in 2nd file compared to 1st file.
                  -3 to display matching lines.
                  -i to do case sensitive comparison.

     Example: comm 1 2
                                           1
                                           2
                                           3
4
5
6
                                           7
                                           8
                                           9
                  10
                  11

                  16




No comments:

Post a Comment