-1

On Ubuntu 14.04 I have files that are in different sub-directories but have same filename. i.e.:

dirA/file01.jpg, dirA/file02.jpg, dirA/file03.jpg

dirB/file01.jpg, dirB/file02.jpg, dirB/file03.jpg

dirC/file01.jpg, dirC/file02.jpg, dirC/file03.jpg

I want to copy all the files (about 1000) contained in different sub-directories (about 200) recursively into a separate single directory (/home/user/temp/).

Since they have identical filenames I want to rename all 1000 individual files appending their respective directories to the filename, thus making them unique, like this:

/home/user/temp/dirA-01.jpg,
/home/user/temp/dirA-02.jpg,
/home/user/temp/dirA-03.jpg

/home/user/temp/dirB-01.jpg,
/home/user/temp/dirB-02.jpg,
/home/user/temp/dirB-03.jpg,

/home/user/temp/dirC-01.jpg
/home/user/temp/dirC-02.jpg
/home/user/temp/dirC-03.jpg

All (1000) files should be stored in the same final directory (home/user/temp).

I tried using ls, then find, then rename, then mv, then cp with too many problems to list. If my PERL was up to scratch I would have nailed this in a minute but it's been 15 years since I've used it... sob sob... Can anyone help with something snappy and not too complicated? Your help is very much appreciated.

Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
Edy
  • 1
  • 1
  • Thank you guys for marking my question as already answered. My limited knowledge of coding doesn't permit me to understand the elaborate answers enough to verify that they work for me. I do know that the answer indicated by the link at the top of my question does not change the filename to include the directory name. So, it really doesn't address the issue. I appreciate your feedback. The answer from Cyrus (below) hits the nail on the head! Smooth, easy and does exactly what I needed. Thanks everyone. – Edy Nov 01 '15 at 00:01

1 Answers1

0
find "$SRC" -name '*.jpg' -exec perl -e'
   for (@ARGV) {
      $o = $_;
      s{^\Q$ENV{SRC}/}{};
      s{/file}{-};
      $n = "$ENV{DST}/$_";
      if (-e $n) {
         warn("rename $o to $n: Already exists\n");
      } elsif (!rename($o, $n)) {
         warn("rename $o to $n: $!\n");
      }
   }
' {} +

if -e $n makes sure you don't overwrite anything by accident.

$SRC and $DST are the source and destination folders respectively.

ikegami
  • 367,544
  • 15
  • 269
  • 518