Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux find and copy files with same name to destination folder do not overwrite

Tags:

linux

find

cp

I want to find and copy all files with *.jpg in one folder includes its sub folder to another folder I use

find /tempL/6453/ -name "*.jpg" |  xargs  -I  '{}' cp {} /tempL/;

but it overwrite files with same name

for example in /tempL/6453/, there are test (1).jpg test (2).jpg and folder 1, in /tempL/6453/1/, there are also have files with the same name test (1).jpg test (2).jpg

If I use the above command, there are only two files test (1).jpg test (2).jpg in /tempL/, it can not copy all files to /tempL/.

What I want is to copy all files to /tempL/, when there are same file name, just rename them, how to?

like image 453
yaya hoho Avatar asked Jul 29 '16 03:07

yaya hoho


2 Answers

What I want is to copy all files to /tempL/, when there are same file name, just rename them, how to?

1) If you only do not what overwrite cp --backup will give you a backup for existing file, with --suffix option of cp, you can also specify the suffix to be used for backup.

2) --parents option of cpwill keep directory tree, i.e. files in folder 1 will be copy to new created 1 folder.

3) If you want to customize your rename processing, you can not use cp command only. write script for it and call it to process the result of find

like image 153
gzh Avatar answered Sep 30 '22 15:09

gzh


Install "GNU parallel" and use:

find /tempL/6453/ -name "*.jpg" | parallel 'cp {} ./dest-dir/`stat -c%i {}`_{/}'

{/}  ................. gets filename with no full path

I think the same approach should be possible with xargs, but learning about parallel was amazing for me, it gives us many beautiful solutions.

I recommend using echo before cp in order to test your command

like image 20
SergioAraujo Avatar answered Sep 30 '22 13:09

SergioAraujo