How to compare two files in Linux command line

You can compare two text files in Linux using the following command-line tools:
diff
vim / vimdiff
These tools are already installed “out-of-the-box” in most Linux distributions.

Example files to compare (file1, file2):

[tuxfixer@tuxfixer ~]$ cat file1
orange
blue
yellow
red
pink
[tuxfixer@tuxfixer ~]$ cat file2
blue
yellow
purple
black
pink
green

1. Comparing using diff

diff compares two files line-by-line and displays what needs to be changed in 1st file to match 2nd file.

Interpretation of results:
(a): add
(d): delete
(c): change
(<): line present in 1st file only
(>): line present in 2nd file only

Example:

[tuxfixer@tuxfixer ~]$ diff file1 file2
1d0
< orange
4c3,4
< red
---
> purple
> black
5a6
> green

Interpretation of above example:
(1d0): delete 1st line (orange) in file1 to match file2
(4c3,4): change 4th line (red) in file1 to 3rd line (purple) and 4th line (black) to match file2
(5a6): in file1 below 5th line add 6th line (green) to match file2

2. Comparing using vim / vimdiff

vim executed with parameter -d works like diff command. You can compare: two, three and four files, vim will open all of them and will display changes between them. You can alternatively execute vimdiff, which will also launch vim in diff mode.

Example:

[tuxfixer@tuxfixer ~]$ vim -d file1 file2

or

[tuxfixer@tuxfixer ~]$ vimdiff file1 file2

vim_diff

Interpretation:
red highlighted text: line differs between file1 and file2
light-yellow highlighted text: line present in file1 only or in file2 only
light-blue highlighted dashed line: separator

Share on: Share on FacebookShare on Google+Tweet about this on TwitterShare on StumbleUponShare on LinkedInPin on PinterestBuffer this pageShare on TumblrDigg thisFlattr the authorShare on RedditShare on VKShare on Yummly
Liked it? Take a second to support tuxfixer.com on Patreon!
Hadoop Developer Training

Leave a Reply

Name *
Email *
Website