web-dev-qa-db-ja.com

ファイル名に基づいてディレクトリツリーを作成する

次の構造のファイルが多数あります。

[Lion] 2015 Africa Book.pdf
[Lion] 2015 Africa Magazine.pdf
[Lion] 2016 Africa Book.pdf
[Lion] 2016 Africa Magazine.pdf
[Lion] 2015 Asia Book.pdf
[Lion] 2015 Asia Magazine.pdf
[Lion] 2016 Asia Book.pdf
[Lion] 2016 Asia Magazine.pdf
[Tiger] 2016 Africa Book.pdf
[Tiger] 2016 Africa Magazine.pdf
[Tiger] 2015 Asia Book.pdf
[Tiger] 2015 Asia Magazine.pdf
[Tiger] 2016 Asia Book.pdf
[Tiger] 2016 Asia Magazine.pdf

等.

基本的に、ファイルは次のパターンに従います。[{animal}] {year} {location} {format}.{ext}

このようなディレクトリ構造を持つようにファイルを移動するにはどうすればよいですか?

Animal stuff
├── Lion
│   ├── 2015 - Africa
│   │   ├── [Lion] 2015 Africa Book.pdf
│   │   └── [Lion] 2015 Africa Magazine.pdf
│   ├── 2015 - Asia
│   │   ├── [Lion] 2015 Asia Book.pdf
│   │   └── [Lion] 2015 Asia Magazine.pdf
│   ├── 2016 - Africa
│   │   ├── [Lion] 2016 Africa Book.pdf
│   │   └── [Lion] 2016 Africa Magazine.pdf
│   └── 2016 - Asia
│       ├── [Lion] 2016 Asia Book.pdf
│       └── [Lion] 2016 Asia Magazine.pdf
└── Tiger
    ├── 2015 - Africa
    │   ├── [Tiger] 2015 Africa Book.pdf
    │   └── [Tiger] 2015 Africa Magazine.pdf
    ├── 2015 - Asia
    │   ├── [Tiger] 2015 Asia Book.pdf
    │   └── [Tiger] 2015 Asia Magazine.pdf
    ├── 2016 - Africa
    │   ├── [Tiger] 2016 Africa Book.pdf
    │   └── [Tiger] 2016 Africa Magazine.pdf
    └── 2016 - Asia
        ├── [Tiger] 2016 Asia Book.pdf
        └── [Tiger] 2016 Asia Magazine.pdf
1
megascrapper

試してみてください:

find . -maxdepth 1 -type f -exec bash -c '
    animal=${1%% *}; 
    year=${1#* }; year=${year% *};
    mkdir -p "${animal//[][]}/${year/ / - }" && mv "$animal $year"'*' "${animal//[][]}/${year/ / - }/"
' _ {} \; 2> /dev/null

結果:

$ tree
.
├── Lion
│   ├── 2015 - Africa
│   │   ├── [Lion] 2015 Africa Book.pdf
│   │   └── [Lion] 2015 Africa Magazine.pdf
│   ├── 2015 - Asia
│   │   ├── [Lion] 2015 Asia Book.pdf
│   │   └── [Lion] 2015 Asia Magazine.pdf
│   ├── 2016 - Africa
│   │   ├── [Lion] 2016 Africa Book.pdf
│   │   └── [Lion] 2016 Africa Magazine.pdf
│   └── 2016 - Asia
│       ├── [Lion] 2016 Asia Book.pdf
│       └── [Lion] 2016 Asia Magazine.pdf
└── Tiger
    ├── 2015 - Asia
    │   ├── [Tiger] 2015 Asia Book.pdf
    │   └── [Tiger] 2015 Asia Magazine.pdf
    ├── 2016 - Africa
    │   ├── [Tiger] 2016 Africa Book.pdf
    │   └── [Tiger] 2016 Africa Magazine.pdf
    └── 2016 - Asia
        ├── [Tiger] 2016 Asia Book.pdf
        └── [Tiger] 2016 Asia Magazine.pdf
0
αғsнιη