Ubuntu – Recursively number directories

command linedirectorydirectory-structurefindrename

I have the following directory structure:

$ directory tree Data
Data
├── Mercury
├── Venus
├── Earth
│   ├── Australia
│   └── Asia
│     └── Japan
|       └── Hokkido   
├── Mars
    ├── HellasBasin
    └── SyrtisCrater

How can rename/number/label all the directories recursively to get a result similar to the following?

Data
    ├── 01
    ├── 02
    ├── 03
    │   ├── 031
    │   └── 032
    │     └── 0321
    |       └── 03211   
    ├── 04
        ├── 041
        └── 042

The idea is to rename the whole tree with new names (numbers, letters or combination of them). They don't necessary have to have labels like 03211.

Thanks in advance for your time.

Best Answer

Using bash:

#! /bin/bash
rename_count ()
{
    count=1
    for i in *
    do
        new="$1$count"
        mv "$i" "$new"
        # if a directory, recurse into it.
        [[ -d "$new" ]] && (cd "$new"; rename_count "$new")
        ((count++))
    done
}
shopt -s nullglob
cd "$1"
rename_count ""

Initially:

$ tree foo
foo
├── a
│   ├── d
│   │   └── g
│   ├── e
│   │   └── g
│   └── f
│       └── g
├── b
│   ├── d
│   │   └── g
│   ├── e
│   │   └── g
│   └── f
│       └── g
└── c
    ├── d
    │   └── g
    ├── e
    │   └── g
    └── f
        └── g

12 directories, 9 files

Then:

$ ./foo.sh foo
$ tree foo
foo
├── 1
│   ├── 11
│   │   └── 111
│   ├── 12
│   │   └── 121
│   └── 13
│       └── 131
├── 2
│   ├── 21
│   │   └── 211
│   ├── 22
│   │   └── 221
│   └── 23
│       └── 231
└── 3
    ├── 31
    │   └── 311
    ├── 32
    │   └── 321
    └── 33
        └── 331

12 directories, 9 files