-2

find if files in one directory recursively exists in another directory recursively in linux bash and print exists or not exists

lets say you have

  • pth1/dirA/file1 pth1/dirA/DirB/file2 and
  • pth2/dirA/file1 pth2/dirA/DirB/file3

I want a report that

file1 exists 
files2 dont exist in pth2
files3 dont exist in pth1

i have found that code that works for current level for both directories, but i cant make it work recursively taken from here

pth1="/mntA/newpics";
pth2="/mntB/oldpics";
for file in "${pth1}"/*; do
    if [[ -f "${pth2}/${file##*/}" ]]; then
       echo "$file exists";
    fi
done

How I can do it to work recursively on both paths?

2
  • It would be helpful with larger example set size Commented Feb 25 at 22:16
  • 1
    Given pth1/dirA/file1, are you wanting to see if there is a file called file1 anywhere at all underneath your pth2/dirA? Or must it be at the same relative place? What about comparing file contents, or are you just interested in the names? Commented Feb 25 at 22:19

2 Answers 2

0

I did it with another method. I find all files in one directory, strip their path, then I can save the results in two different files and compare them with meld or other program, or I can compare finds directly with meld.

Note that I sort files and choose only unique files and not duplicates in results. Also, I am interested only in files that their filename ends in "jpg" extension.

pth1="/mnt/oldfiles";
pth2="/mnt/newfiles";

and then

(find "${pth1}"/ -exec basename {} \; | grep "jpg$" | sort | uniq )  > a.txt;
(find "${pth2}"/ -exec basename {} \; | grep "jpg$" | sort | uniq )  > b.txt;
meld a.txt b.txt

OR diretly

meld <(find "${pth1}"/ -exec basename {} \; | grep "jpg$" | sort | uniq )  <(find "${pth2}"/ -exec basename {} \; | grep "jpg$" | sort | uniq )

UPDATE: if one directory is much larger than other, the direct command dont work (MILD opens without both commands finish).

2
  • And what if there are files with same names, but different contents, or same contents, but different names? Commented Feb 25 at 21:18
  • at this case, i know very well the content, same name same content. Commented Feb 26 at 12:32
0

It's not terribly clear what you want, but I think this will do it. This command compares all files under /path/1 to those under /path/2, checking for existence and equality.

diff --brief --recursive /path/1 /path/2

Worked example

# Create some files
mkdir -p 1/{x,y} 2/{x,z}
touch 1/{x,y}/file1
date | tee 2/x/file1 >2/z/date

# Show what we have
tree 1 2
1
├── x
│   └── file1
└── y
    └── file1
2
├── x
│   └── file1
└── z
    └── date
4 directories, 4 files

# Compare the two directory trees
diff --brief --recursive 1 2
Files 1/x/file1 and 2/x/file1 differ
Only in 1: y
Only in 2: z

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .