Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a directory structure like below where the structure is known, and the file names repeat themselves. I want to rename the files so they are unique, so that

a/0/widgets/AL/part-1.gz becomes

a/0/widgets/AL/a_0_widgets_AL_part-1.gz,

and

b/0/widgets/AL/part-1.gz becomes

b/0/widgets/AL/b_0_widgets_AL_part-1.gz, etc.

This way I can copy all of the files into one top level directory while keeping all known information about the file and not clobbering any files because of file name repeats.

Suggestions?

├── a
│   ├── 0
│   │   └── widgets
│   │       ├── AL
│   │       │   ├── part-1.gz
│   │       │   └── part-2.gz
│   │       ├── AK
│   │       │   ├── part-3.gz
│   │       │   └── part-4.gz
| ....

├── b
│   ├── 0
│   │   └── widgets
│   │       ├── AL
│   │       │   ├── part-1.gz
│   │       │   └── part-2.gz
│   │       ├── AK
│   │       │   ├── part-3.gz
│   │       │   └── part-4.gz
| ....
share|improve this question
add comment

2 Answers 2

Try this:

find . -type f -print | while read path; do
  dir="$(dirname "$path")"
  prefix="${dir:2}"
  prefix="${prefix//\//_}"
  mv "$path" "$dir/${prefix}_$(basename "$path")"
done
share|improve this answer
add comment
up vote 0 down vote accepted

I came up with this hacky solution. Easier to do in Python than Bash IMHO.

#!/usr/bin/env python                                               

import os                                                           

for root, dirs, files in os.walk('/mnt/orig_data'):            
    if len(files) > 0:                                              
        for file in files:                                          
            parts = root.split('/')                                 
            new_file = '%s_%s' % ('_'.join(parts[-4:]), file, )     
            os.rename('/'.join([root, file]),                       
                  '/'.join([root, new_file]))                   
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.