Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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
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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .