I need to diff two directories:
A: /path1/
B: /path2/
- The directory A contains all files and subdirectories that are also contained in B.
- The files in A (and in its subdirectories) can have different contents of the equivalent files in B.
- The directory A (and its subdirectories) also has extra files that do not exist in B.
What I would like to achieve is:
- Keep only the files in A that differ from the files in B plus all the extra files that don't exist in B.
- Delete all the other files in A that do not respect the previous rule.
Best Answer
This approach should work:
How it works:
find . -type f
goes through all files in the current directory (A) and its subdirectories.cmp -s {} /path2/{}
silently (-s
) compares the currently processed file ({}
) to the matching file in B (/path2/{}
).If the files are identical, cmp returns true and the
-exec
condition matches.If the
-exec
condition matches,-delete
deletes the file.I suggest replacing
-delete
with-print
before running the actual command to verify if it works as expected.To deal with leftover empty directories, you can execute the command:
-type d
only finds directories.-exec rmdir -p {} \;
executesrmdir -p {}
for every directory that has been found.{}
is the directory that has been found, and the-p
switch makes rmdir remove its empty parent directories as well.2> /dev/null
suppresses the error messages that will arise from trying to delete non-empty or previously deleted directories.Since rmdir cannot delete non-empty directories, this should be the safest way.