Find common files between two directories

I have two directories
Dir 1

/home/sid/release1

Dir 2

/home/sid/release2

I want to find the common files between the two directories

Dir 1 files

/home/sid/release1>ls -lrt
total 16
-rw-r--r--   1 sid cool          0 Jun 19 12:53 File123
-rw-r--r--   1 sid cool          0 Jun 19 12:53 File456
-rw-r--r--   1 sid cool          0 Jun 19 12:53 FileDEF
-rw-r--r--   1 sid cool         17 Jun 19 13:11 Fileabc

Dir 2 files

/home/sid/release2>ls -lrt
total 16
-rw-r--r--   1 sid hot          0 Jun 19 13:02 File456
-rw-r--r--   1 sid  hot          0 Jun 19 13:02 FileDEF
-rw-r--r--   1 sid  hot         17 Jun 19 13:10 Fileabc

I want the output to show the common files between these directories

File456
FileDEF
Fileabc

Example: you have to directories a and b

Use the comm command on the output of ls:

comm -12 <(ls a) <(ls b)

This works in modern shells, the <(ls a) thing is called process substitution. comm -12 means show only entries that are the same. Play with changing the options for comm: -1 -2 -3 and see. The example is bash syntax.

1 Like
>ls /tmp/a
1  2  3  4  456  5  File  File123  File456  Filebc  FileDEF
>ls /tmp/v
1  4  File123  File456  FileDEF
>cd /tmp/a
>ls `ls /tmp/v` 2>&1 | grep -iv 'cannot'
1
4
File123
File456
FileDEF
>cd /tmp/v
>ls `ls /tmp/a` 2>&1 | grep -iv 'cannot'
1
4
File123
File456
FileDEF
>

If your shell does not have <( .. ) (process substitution), you could try using temporary files ( or named pipes)

--
Or try something like:

ls Dir1 Dir2 | awk 'A[$0]++'

Nice idea, but for the paranoid (e.g. me) it should be

(ls Dir1; ls Dir2) | awk 'A[$0]++'

in case Dir1 contains a file Dir2: or vice versa.

Thanks, and well, if you want to avoid that corner case, yes that would avoid that.
Using command grouping instead, will save an extra subshell.

{ ls Dir 1; ls Dir 2;} | awk 'A[$0]++'