Search code examples
bashgnupg

bash script to compare file names in one directory with file names in another while ignoring file extensions


I am trying to compare the files in one directory with those in another. Let's take directories test 1 and test2. If test 1 contains a file named 123.JPG and if test 2 contains a file named 123.JPG.gpg I would then take no course of action: 123.JPG has already been encrypted. However if no match was successful I would then run gpg to encrypt 123.JPG.

I found this script elsewhere which I tried to modify to achieve the above but to no avail:

cd source
for x in *; do
  set -- "…/dest/${x%.*}".*
  if [ $# -eq 1 ] && ! [ -e "$1" ]; then
    echo "$x has not been converted"
  elif [ $# -gt 1 ]; then
    echo "$x has been converted to more than one output file: " "$@"
  else
    echo "$x has been converted to $1"
  fi
done

Can anyone please help?

Thank you


Solution

  • If you have GNU's find and you can use the printf option, then the follwing command:

    comm -23 <(find A -type f -printf '%f.gpg\n'|sort) <(find B -type f -printf '%f\n'|sort)
    

    will give you a list of missing files:

    If directory A is:

    A
    ├── 123.JPG
    ├── 456.JPG
    └── 789.JPG
    

    And directory B is:

    B
    ├── 123.JPG.gpg
    └── 456.JPG.gpg
    

    The output would be 789.JPG.gpg which is the missing encrypted file - it does not exist in directory B, and a file with a similar name but without the extension, does exist in directory A.

    You can then use the result list to encrypt the missing files.

    Please notice that this command works recursively.