bash - copying multiple files with the same name

I would like to copy files that are under the same name but in different folders into destdir. The issue is about not overwriting them in destdir.

Basically this could be enough, although I have no clue how to rename each of the file. As for now they all being overwritten:

$ cp /src/folder/*/file ~/dest/*


Solution 1:

Here's one method:

cd /src/folder
for f in */file; do
    cp -v "$f" ~/dest/"${f//\//_}"
done

that will copy /src/folder/foobar/file to ~/dest/foobar_file which should be unique

Solution 2:

You can see whether the --backup option of cp is available (I believe it isn't on MacOS, but I might be wrong):

 cp --backup=t /src/folder/*/file /dest

will create file.jpg.~1~, file.jpg.~2~ and so on.