2

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.

  • Now this is an interesting variant on a usually boring subject :) – Jacob Vlijm Feb 17 '18 at 13:32
  • 6
    Is there actually a locale in which planet names sort in solar-system order... or did you make up that tree listing? – steeldriver Feb 17 '18 at 13:43
  • @ Jacob : I spent several hours trying to do this myself before deciding to bother you guys :) I'm new to Linux. This is beyond my current knowledge and skills. – alien250 Feb 17 '18 at 14:16
  • 1
    @ steeldriver : I made that up for this question :) – alien250 Feb 17 '18 at 14:21
6

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
  • @steeldriver it could, and I'll add that. Thanks! – muru Feb 17 '18 at 14:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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