bashfindcmp

How to delete the same files in the two directories with comparison in linux?


I want to delete the same files in two directories. Both have so many files with the same name. If two files are same I want to delete in the first directory. I am not sure whether linux shell is better choice or python would be better.

  1. $HOME/bin
  2. $HOME/cin

In some search, there is an close answer for comparison.

find cin -type f -exec cmp '{}' "bin/{}" \;

But this is not working because the first output of find, {} contains "cin/" directory name such as "cin/file1". So the second "bin/{}" has "bin/cin/file1". Then comparison error occurs

cmp: bin/cin/file1: No such file or directory

how to compare cin/file1 and bin/file1?


Solution

  • You can use this find command:

    find cin -type f -exec bash -c 'f="${1#cin/}"; cmp "cin/$f" "bin/$f"' _ {} \;
    

    It executes the command inside bash -c for all regular files in cin directory.

    The upper directory is removed by the bashism ${1#...} and the variable f is set to relative path.