Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare file names in two directories in shell script?

Tags:

bash

shell

Right now, this is what my code looks like:

#!/bin/bash

Dir1=$1
Dir2=$2

for file1 in $Dir1/*; do
    for file2 in $Dir2/*; do
        if [[ $file1 == $file2 ]]; then
            echo "$file1 is contained in both directories"
        fi
    done
done

I am trying to compare the file names of the two directories entered and say that the file is in both directories if the filename matches. When I try to run it though, nothing is echo-ed even though I have the same file in both directories.

like image 924
Apple Avatar asked Jan 29 '15 01:01

Apple


2 Answers

Files that are in both Dir1 and Dir2:

find "$Dir1/" "$Dir2/" -printf '%P\n' | sort | uniq -d

Files that are in Dir1 but not in Dir2:

find "$Dir1/" "$Dir2/" "$Dir2/" -printf '%P\n' | sort | uniq -u

Files that are in Dir2 but not in Dir1:

find "$Dir1/" "$Dir1/" "$Dir2/" -printf '%P\n' | sort | uniq -u
like image 96
Innocent Bystander Avatar answered Nov 27 '22 23:11

Innocent Bystander


If you want to know what's common to two directories then this is another way with much less coding.

#!/bin/bash

comm -12 <(ls -F $1) <(ls -F $2)

See man comm for more information about the comm utility.

like image 36
user3439894 Avatar answered Nov 28 '22 01:11

user3439894