Kavintha Kulasingham
Kavintha Kulasingham

Reputation: 34

How to compare filenames in bash

I need to compare if "dir1" has the same files as "dir2" and ideally remove the similar contents in "dir2".

So far i have tried using the find command:

    $ find "$dir1" "$dir2/" "$dir2/" -printf '%P\n' | sort | uniq -u^C

But this doesn't work cause, while the filename are similar, the extension of the files are different in the two folders.

so how do i go about comparing filenames in bash?

Upvotes: 1

Views: 1174

Answers (1)

Tom Fenech
Tom Fenech

Reputation: 74605

Sounds like you just need to use a loop:

for path in "$dir1"/*; do
  base=${path##*/}  # remove everything up to and including the last / to get the name
  if [ -e "$dir2/$base" ]; then
    echo rm -r "$dir2/$base"
  fi
done

Loop through everything in $dir1 and if $dir2 has a file with the same name, then remove it.

Remove the echo when you're happy that the script is going to remove the right files.

Upvotes: 2

Related Questions