# Linux – How to find the files existing in one directory but not in the other directory?

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 list out the names of those files that are present in one of these directories say d1 and not present in the other directory say d2.

In order to do that we must be familiar with either the diff command or the comm command, as both these 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 3 20:03 d1
drwxr-xr-x 4 immukul staff 128 Jul 3 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 3 20:03 1.txt
-rw-r--r-- 1 immukul staff 0 Jul 3 20:03 3.txt
-rw-r--r-- 1 immukul staff 0 Jul 3 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 3 20:03 2.txt
-rw-r--r-- 1 immukul staff 0 Jul 3 20:03 3.txt

Now we want only those files that are present in the first directory and not in the second directory. For that, we just need to write the following command to the terminal −

diff -r d1 d2 | grep d1 | awk '{print $4}' Let’s break the above command to understand it better − • The diff -r d1 d2 commands show the files present in d1 and not in d2 along with the changes of the files present in d1. • The grep d1 command shows the files of d1 only. • The awk ‘{print$4}’ is used to print the name of those files.

## Output

immukul@192 linux-questions-code % diff -r d1 d2 | grep d1 | awk '{print \$4}'
1.txt
5.txt

We can also achieve the same output with the help of the comm command that linux provides us with.

Just type the following command to the terminal −

comm -23 <(ls d1 |sort) <(ls d2|sort)

## Output

immukul@192 linux-questions-code % comm -23 <(ls d1 |sort) <(ls d2|sort)
1.txt
5.txt
Updated on 29-Jul-2021 11:20:02