Copy files from multiple directories into one directory without overwriting them

I have several directories and all those directories have .dat files in them. I want to copy all those .dat files to one directory say "collected_directory"

The problem is I don't want to overwrite files. So, if two file names match, I don't want the old file to be overwritten with a new one.

I know how to copy files from multiple directories to one directory:

find <start directory> -iname "<all my file_type>" -exec cp {} <target_dir> \;

But how to handle the case where no overwrite occurs rather the same file names get a new name like abc_1.dat if abc.dat already exists in "collected_directory"?

I am using Linux with BASH.

The GNU version of cp has the -n (do not overwrite an existing file) option.

1 Like