Andrew
Andrew

Reputation: 1167

using cp command to copy one set of files to another set (with same names) without overwrite and with renaming

Say I have a bunch of files in folder A:

1.txt
2.txt
3.txt
...

And a bunch of files in folder B, with the same names.

I want to move all the files from folder B into folder A, without losing any files. This means that some files need to be renamed. E.g., to 1cp.txt, 2cp.txt, 3cp.txt, ...

As I understand it, using

cp folderB/*.txt folderA/

will overwrite all files in folder A. Whereas, if I use the -n flag, this means that nothing will be copied, because -n prevents overwriting.

Does anyone know how I can achieve this copy and rename procedure, so that all files from both folders are retained?

Upvotes: 0

Views: 3759

Answers (2)

crazy_prog
crazy_prog

Reputation: 1099

First, you can rename it.

$ rename -n 's/\d{5}(\d{3})\.JPG$/BeachPics_$1\.jpg/' *.JPG
00000123.JPG renamed as BeachPics_123.jpg
00000124.JPG renamed as BeachPics_124.jpg
00000125.JPG renamed as BeachPics_125.jpg

and then copy it.

cp folderB/*.txt folderA/

Upvotes: 0

favoretti
favoretti

Reputation: 30167

You can use -b (backup each existing file). --backup accepts arguments to control behavior. Otherwise you can create a bit more lines and check for your files in a more elaborated script.

Upvotes: 2

Related Questions