How to compare the files available in two directories using diff command in Linux?

LinuxOperating SystemOpen Source

Let’s consider a case where we have two directories, say, d1 and d2 and both these directories contain some files, which may be the same or different. Now we want to compare the files that are present in both these directories and by comparison we need to print out what files are different, what files are the same and in what directory.

In order to do that we must be familiar with either the diff command as the diff commands can be used to solve the above problem.

Let’s first explore the diff command, which is short for difference. This command is used to find the difference between two files as it compares both the files line by line.

Let’s explore the case where we have two directories d1 and d2 and both these directories contain some files in them.

Consider the terminal output to depict these two directories shown below −

immukul@192 linux-questions-code % ls -ltr
total 0
drwxr-xr-x 5 immukul staff 160 Jul 5 20:03 d1
drwxr-xr-x 4 immukul staff 128 Jul 5 20:03 d2

Now the contents of the first directory d1 looks something like this −

immukul@192 d1 % ls -ltr
total 0
-rw-r--r-- 1 immukul staff 0 Jul 5 20:03 1.txt
-rw-r--r-- 1 immukul staff 0 Jul 5 20:03 3.txt
-rw-r--r-- 1 immukul staff 0 Jul 5 20:03 5.txt

Now the contents of the first directory d2 looks something like this −

immukul@192 d2 % ls -ltr
total 0
-rw-r--r-- 1 immukul staff 0 Jul 5 20:03 2.txt
-rw-r--r-- 1 immukul staff 0 Jul 5 20:03 3.txt

Now we want to know the difference between the directories d1 and d2 and in order to print the difference we can make use of the command shown below −

diff -q d1 d2 | cut -f2 -d ','

Output

Only in d1: 1.txt
Only in d2: 2.txt
Only in d1: 5.txt

Another command that we can make use of is also shown below −

diff -qr d1 d2

Output

Only in d1: 1.txt
Only in d2: 2.txt
Only in d1: 5.txt
raja
Published on 29-Jul-2021 11:46:16
Advertisements